简体   繁体   中英

Testing a private method in a final class

I want to test a private method in a final utitlity class.

1. The class itself:

The class signature is:

public final class SomeHelper {

    /** Preventing class from being instantiated */
    private SomeHelper() {
    }

And there is the private method itself:

private static String formatValue(BigDecimal value)

The test is allready written, but earlier, the method was in a non-utility non-final class without a private constructor.

The test is using @RunWith(Parameterized.class) already.

Now all I get is an exception:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class com.some.package.util.SomeHelper
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

2. The test

The most important line in this test is:

String result = Whitebox.invokeMethod(mValue, "formatValue", mGiven);

Is there a way of making the test work?

You don't need to test private methods.

But you SHOULD test the ones that use it. If methods that call your private methods are working as you expect, you can assume private methods are working correctly.

Why?

Nobody will call this method alone, so unit test for it is unnecessary.

You don't need to test private method, because it'll not be called directly. But if it realizes some so complicated logic, you want to do this, you should consider extracting class.

What I finally did is based on the answer from question How do I test a class that has private methods, fields or inner classes? that @Sachin Handiekar provided in a comment.

It's not the most beautiful way, considering that private methods should not be tested, but I wanted it tested and I was just curious.

This is how I did it.

Class someHelper = SomeHelper.class;
Method formatValue = someHelper.getDeclaredMethod("formatValue ", BigDecimal.class);
formatValue.setAccessible(true);
String result = (String) formatValue .invoke(new String(), mGiven);

And it works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM