【问题标题】:Use Powermockito to check if a private method is called or not使用 Powermockito 检查是否调用了私有方法
【发布时间】:2016-06-02 12:02:12
【问题描述】:

我想检查是否使用 powermockito 执行了我的类的私有方法进行测试。

假设我有这个类要测试:

public class ClassToTest {
    public boolean methodToTest() {
        //doSomething (maybe call privateMethod or maybeNot)
        return true;
    }

    //I want to know if this is called or not during the test of "methodToTest".
    private void privateMethod() {
        //do something
    }
}

当我测试“methodToTest”时,我想检查它是否返回正确的结果,以及它是否执行私有方法“privateMethod”。 搜索其他讨论,我编写了这个使用 powermockito 的测试,但它不起作用。

public class TestClass {

    @Test
    testMethodToTest(){
        ClassToTest instance = new ClassToTest();
        boolean result = instance.methodToTest();
        assertTrue(result, "The public method must return true");

        //Checks if the public method "methodToTest" called "privateMethod" during its execution.
        PowerMockito.verifyPrivate(instance, times(1)).invoke("privateMethod");
    }
}

当我使用调试器时,最后一行 (PowerMockito.verifyPrivate...) 似乎没有检查私有方法是否在测试期间执行过一次,而是它似乎执行了私有方法本身。此外,测试通过但使用调试器我确信在调用“instance.methodToTest()”期间不会执行私有方法。 怎么了?

【问题讨论】:

  • 您正在尝试验证类的真实实例,而不是模拟!
  • 嗯我错过了一些东西,这样做的正确方法是什么?测试模拟的行为是否正确?我认为模拟对象仅用于隐藏要测试的类与其他对象的引用,并且要测试的类的实例应该是真实的。
  • 你为什么关心它是否被调用?测试应该关心的是公共方法是否正确,而不应该关心是否调用了特定的私有方法。

标签: java unit-testing junit powermockito


【解决方案1】:

如果没有 PowerMockito,我会做得更简单。考虑一下(它是某种 Spy 对象):

public class TestClassToTest {

    private boolean called = false;

    @Test
    public void testIfPrivateMethodCalled() throws Exception {
        //given
        ClassToTest classToTest = new ClassToTest() {
            @Override
            void privateMethod() {
                called = true;
            }
        };

        //when
        classToTest.methodToTest();

        //then
        assertTrue(called);
    }
}

这需要将 privateMethod() 更改为 package-private(但这并没有错)。

但请记住,测试实施是一种不好的做法,并且可能导致脆弱的测试。相反,您应该只测试结果。

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多