Java 使用Powermockito检查是否调用了私有方法
我想检查是否使用powermockito执行了要测试的类的私有方法 假设我要测试这个类:Java 使用Powermockito检查是否调用了私有方法,java,unit-testing,junit,powermockito,Java,Unit Testing,Junit,Powermockito,我想检查是否使用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
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()”期间不会执行私有方法。
怎么了?如果没有PowerMockito,我会用更简单的方法。考虑这个(它是某种间谍对象): 这需要将
privateMethod()
更改为package private(但这没有错)
但请记住,测试实现是一种糟糕的做法,可能会导致脆弱的测试。相反,您应该只测试结果 您正在尝试验证类的真实实例,而不是模拟实例!嗯,我错过了一些东西,正确的方法是什么?测试模拟的行为是否正确?我假设mock对象只用于隐藏要测试的类与其他对象之间的引用,并且要测试的类的实例应该是一个真实的实例。为什么要关心它是否被调用?测试应该关心的是公共方法是否正确,而不应该关心是否调用了特定的私有方法。
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);
}
}