Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
dziki Avatar asked Jan 07 '23 15:01

dziki


1 Answers

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.

like image 106
Jordi Castilla Avatar answered Jan 19 '23 22:01

Jordi Castilla