Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this article, we'll briefly explain why testing private methods directly is generally not a good idea. Then we'll demonstrate how to test private methods in Java if it's necessary.

2. Why We Shouldn't Test Private Methods

As a rule, the unit tests we write should only check our public methods contracts. Private methods are implementation details that the callers of our public methods are not aware of. Furthermore, changing our implementation details should not lead us to change our tests.

Generally speaking, urging to test a private methods highlights one of the following problems:

  • We have dead code in our private method.
  • Our private method is too complex and should belong to another class.
  • Our method was not meant to be private in the first place.

Hence, when we feel like we need to test a private method, what we should really do is fix the underlying design problem instead.

3. An Example: Remove Dead Code From a Private Method

Let's showcase a quick example of that.

We're going to write a private method that will return the double of an Integer. For null values, we want to return null:

private static Integer doubleInteger(Integer input) {
    if (input == null) {
        return null;
    }
    return 2 * input;
}

Now, let's write our public method. It will be the only entry point from outside the class.

This method receives an Integer as an input. It validates that this Integer is not null, otherwise, it throws an IllegalArgumentException. After that, it calls the private method to return twice the Integer‘s value:

public static Integer validateAndDouble(Integer input) {
    if (input == null) {
        throw new IllegalArgumentException("input should not be null");
    }
    return doubleInteger(input);
}

Let's follow our good practice and test our public method contract.

First, let's write a test that ensures that an IllegalArgumentException is thrown if the input is null:

@Test
void givenNull_WhenValidateAndDouble_ThenThrows() {
    assertThrows(IllegalArgumentException.class, () -> validateAndDouble(null));
}

Now, let's check that a non-null Integer is correctly doubled:

@Test
void givenANonNullInteger_WhenValidateAndDouble_ThenDoublesIt() {
    assertEquals(4, validateAndDouble(2));
}

Let's have a look at the coverage reported by the JaCoCo plugin:

Code coverage of our methodsAs we can see, the null check inside our private method is not covered by our unit tests. Should we test it then?

The answer is no! It's important to understand that our private method doesn't exist in a vacuum. It will only be called after the data is validated in our public method. Thus, the null check in our private method will never be reached: It is dead code and should be removed.

4. How to Test Private Methods in Java

Assuming we're not discouraged of testing our private method, let's explain how we can do it concretely.

To test it, it would be helpful if our private method had another visibility. The good news is that we'll be able to simulate that with reflection.

Our encapsulating class is called Utils. The idea is to access the private method called doubleInteger which accepts an Integer as a parameter. Then we'll modify its visibility to be accessible from outside the Utils class. Let's see how we can do that:

private Method getDoubleIntegerMethod() throws NoSuchMethodException {
    Method method = Utils.class.getDeclaredMethod("doubleInteger", Integer.class);
    method.setAccessible(true);
    return method;
}

Now, we're able to use this method. Let's write a test that will check that given a null object, our private method returns null. We'll need to apply the method to a parameter that will be null:

@Test
void givenNull_WhenDoubleInteger_ThenNull() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
    assertEquals(null, getDoubleIntegerMethod().invoke(null, new Integer[] { null }));
}

Let's comment a bit more on the usage of the invoke method. The first argument is the object on which we apply the method. As doubleInteger is static, we passed in a null. The second argument is an array of parameters. In this case, we had only one parameter, and it was null.

Lastly, let's demonstrate how we could also test the case of a non-null input:

@Test
void givenANonNullInteger_WhenDoubleInteger_ThenDoubleIt() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    assertEquals(74, getDoubleIntegerMethod().invoke(null, 37));
}

5. Conclusion

In this article, we described why testing private methods is generally not a good idea. Then, we showed how to use reflection to test a private method in Java.

As always, the code is available over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Junit footer banner
6 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!