PowerMockito 正在调用真正的方法而不是模拟的私有方法

2024-03-21

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

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");并像这样嘲笑第二个,PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");。如你所见isDecrementable方法应该返回true, true, false调用时的值,但 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PowerMockito 正在调用真正的方法而不是模拟的私有方法 的相关文章

随机推荐