Testing a private method in a finite class

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

1. The class itself:

Class signature:

public final class SomeHelper {

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

And there is a method of its own:

private static String formatValue(BigDecimal value)

The test has already been written, but previously the method was in a non-useful non-finite class without a private constructor.

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

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. Test

The most important line in this test:

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

Is there a way to do a test job?

+4
source share
3 answers

You do not need to check private methods.

, . , , , , , .

?

, unit test .

+7

, . - , , .

+1

, , , , ?, @Sachin Handiekar .

This is not the most beautiful way, given that private methods should not be tested, but I wanted it to be tested, and I was just curious.

Here 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.

0
source

Source: https://habr.com/ru/post/1629136/


All Articles