在最终类中测试私有方法

时间:2016-02-17 09:21:37

标签: java junit mockito powermock

我想在最终的utitlity类中测试私有方法。

1。课程本身:

班级签名是:

public final class SomeHelper {

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

还有私有方法本身:

private static String formatValue(BigDecimal value)

测试已经完成了,但是之前,该方法是在没有私有构造函数的非实用非final类中。

测试已使用@RunWith(Parameterized.class)

现在我得到的只是一个例外:

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。测试

此测试中最重要的一行是:

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

有没有办法让测试工作?

3 个答案:

答案 0 :(得分:7)

您不需要测试私有方法。

但你应该测试那些使用它的人。如果调用私有方法的方法按预期工作,则可以假设私有方法正常工作。

<强>为什么吗

没有人会单独调用此方法,因此不需要进行单元测试。

答案 1 :(得分:1)

您不需要测试私有方法,因为它不会被直接调用。但如果它意识到一些如此复杂的逻辑,你想要这样做,你应该考虑提取类。

答案 2 :(得分:0)

我最终做的是基于@Sachin Handiekar在评论中提供的问题How do I test a class that has private methods, fields or inner classes?的回答。

这不是最美丽的方式,考虑到私人方法不应该被测试,但我想测试它,我只是好奇。

这就是我做到的。

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

它就像一个魅力。

相关问题