我正在尝试对 A 类进行单元测试,我在其构造函数 getB() 中调用一个方法。我想对这个类 A 进行单元测试,而不在构造函数内调用此方法,以便测试类内的其他方法。
class A {
B b;
public A() {
B = getB();
}
doSomething() {
b.doOtherThing();
}
getB() {
return somethingThatReturnB;
}
}
@Test
class TestA {
@Spy
A a;
@Mock
B b;
@BeforeMethod
public void beforeMethod() {
MockiyoAnnotations.openMocks(this);
}
@Test
public void testMethod() {
doReturn(smt).when(b).doOtherThing();
a.doSomething();
}
}
我尝试了模拟构造函数,但这并没有调用我想要测试的真正方法。
Mockito 有一个
when(systemUnderTest.methodToTest()).thenCallRealMethod();
选项,允许您显式调用真正的方法。不过,您必须为类中的每个方法执行此操作