public class aClass {
public String meth1() {
bClass b = new bClass();
b.meth2();// I don't want to call this method
//buss logic
}
}
public class bClass {
public String meth2() {
// some logic
}
}
目前,我正在为aClass
中的meth1创建一个JUnit测试用例。但是,我不想在bClass
中调用meth2
,只执行aClass
中的总线逻辑。类aClass
和bClass
是固定的-我不能改变他们的代码。
我尝试了很多东西,如@InjectMocks
和doNothing
使用Mockito和PowerMock,但meth2
总是被调用时,我在aClass
调用meth1
。我能做些什么来解决这个问题?
PowerMock拯救:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ aClass.class })
public class TestPowerMock {
@Test
public void shouldBlaBla() throws Exception {
// you can do whatever you want on bMock, because it's a mock
bClass bMock = PowerMockito.mock(bClass.class);
// when aClass instantiates bClass, the mock will be returned
PowerMockito.whenNew(bClass.class).withNoArguments().thenReturn(bMock);
// your test
aClass a = new aClass();
a.meth1();
}
}
点击这里阅读更多