Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

1. Overview

In this tutorial, 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 aren't aware of. Furthermore, changing our implementation details shouldn't lead us to change our tests.

Generally speaking, urging to test a private method 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 wasn't 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'll be the only entry point from outside the class.

This method receives an Integer as an input. It validates that this Integer isn't 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 isn't 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'll 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's dead code and should be removed.

4. How to Test Private Methods in Java

Assuming we're not discouraged, let's explain how to test our private method 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 to ensure 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 explain a bit more about 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.

Finally, let's demonstrate how we can 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 learned why testing private methods is generally not a good idea. Then we demonstrated how to use reflection to test a private method in Java.

As always, the code is available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until next Friday:

>> GET ACCESS NOW

Junit footer banner
6 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!