java - PowerMockito 正在调用真实方法而不是模拟私有(private)方法

标签 java unit-testing junit mockito powermockito

我有一个类,它有一个私有(private)方法并在其主体中调用另一个私有(private)方法。所以我想调用第一个私有(private)方法并模拟第二个。这是一个例子:

public class ClassWithPrivateMethod {

    private int count;

    public ClassWithPrivateMethod() {
    }

    private void countDown() {
        while (isDecrementable())
            count--;
    }

    private boolean isDecrementable() {

        throw new IllegalArgumentException();
//        if (count > 0) return true;
//        return false;
    }
}

和测试类:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithPrivateMethodTest.class)
public class ClassWithPrivateMethodTest {

    private int count;
    private ClassWithPrivateMethod classWithPrivateMethod;

    @Before
    public void setUp() throws Exception {
        count = 3;
        classWithPrivateMethod = PowerMockito.spy(new ClassWithPrivateMethod());
    }

    @Test
    public void countDown() throws Exception {

        Whitebox.setInternalState(classWithPrivateMethod, "count", count);
        PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");

        Whitebox.invokeMethod(classWithPrivateMethod, "countDown");

        int count = Whitebox.getInternalState(classWithPrivateMethod, "count");

        assertEquals(1, count);

        PowerMockito.verifyPrivate(classWithPrivateMethod, times(3)).invoke("isDecrementable");
    }
}

我通过 Whitebox.invokeMethod(classWithPrivateMethod, "countDown"); 调用了第一个私有(private)方法,然后像这样模拟第二个方法,PowerMockito.doReturn(true, true, false).when( classWithPrivateMethod, "isDecrementable");.如您所见,isDecrementable 方法在调用时应返回 truetruefalse 值,但 PowerMockito 正在调用真正的方法.

我正在使用这些依赖项:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.5</version>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.5</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.10.19</version>
</dependency>

我的测试有什么问题?

最佳答案

我发现这一行有错误:

@PrepareForTest(ClassWithPrivateMethodTest.class)

应该是:

@PrepareForTest(ClassWithPrivateMethod.class)

关于java - PowerMockito 正在调用真实方法而不是模拟私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42018713/

相关文章:

node.js - 测试 sails Controller

unit-testing - 什么是 "Stub"?

java - e JUnit 测试是否有可能判断它是否在 Eclipse 中运行(而不是 ant)

java - Android:WebView 是否受 Java 堆限制的影响?

c++ - 如何使这些测试用例代码美观?

java - Appium session ,找不到连接的 Android 设备。显示错误

java - 使用 ArgumentMatcher 时出现 NullPointerException

java - viewHolder 和抽屉导航的问题

java - Google App Engine Blobstore 图像

java - java中的 float 比较以识别模式