Java test class with many private methods

11,656

Solution 1

In theory, your private methods are being used ultimately by one of the public methods, or else they're not used at all. So typically you setup your tests to call the public methods with the necessary context so that it hits your private methods.

The unit tests are primarily testing the compilation unit (i.e. the class). You can unit test methods directly but then they have to be public, which goes against having a nice clean API.

So test your public method enough to hit all the private methods. Private methods are internal mechanics of the class, they don't need to be tested directly.

Solution 2

You can use reflection to achieve this. The Method class has a method called setAcessible(boolean) which enables you to call it even if declared as private/protected/default. See the example below:

YourClass yourClassInstance = new YourClass();
Method yourMethod = YourClass.class.getDeclaredMethod("yourMethod", null);
yourMethod.setAccessible(true);
Object[] parameters = new Object[1];
parameters[0] = "A String parameter";
Object result = yourMethod.invoke(yourClassInstance, parameters);

Solution 3

Some people argue that you should only test your API (i.e. your public methods).

A possible solution is to use package private so that only classes in the same package can access those methods.

Personally, I wouldn't test private methods, I would focus on the public methods behaving as expected. If you feel your private methods carry too much weight, then perhaps they do and you should separate further the functionality.

Share:
11,656

Related videos on Youtube

Kennedy Oliveira
Author by

Kennedy Oliveira

A Java Developer who is interested in Java and Scala Actor Systems and Akka, Domain Driven Design, Reactive Systems and much more.

Updated on June 04, 2022

Comments

  • Kennedy Oliveira
    Kennedy Oliveira almost 2 years

    I have a class that has the responsibility of importing contracts from a CSV to database.

    The class itself has only one public method that starts the import and the other methods are all private (because only the class itself will use, and they hold the logic).

    I'm starting to make tests for this class using Spock and there are many private methods, how should I test it?

    Should I turn them into public to test? Test only the main method, the public one?

    Whats the best?

    • Peter Niederwieser
      Peter Niederwieser over 9 years
      Spock tests are written in Groovy, which means that they can call private (Java) methods. So it's not a technical issue but merely a question of whether you want to go there.
  • Kennedy Oliveira
    Kennedy Oliveira over 9 years
    Thx, i'll test like that!

Related