[英]Mockito and nested method call
我有3節課:
public class SomeDAO {
// that method I'd want to catch and change
public void getObj() { ... }
}
public class MainService {
private Service2 service2;
public void doMain() {
service2.doSomethingAnother();
}
}
public class Service2 {
private SomeDAO someDAO
public void doSomethingAnother() {
someDAO.getObj();
}
}
我需要的是-調用doMain,但是在service2.doSomethingAnother()內部有自定義someDao.getObj() :
public TestClass {
@InjectMocks
private final MainService mainService = new MainService();
@InjectMocks
private final Service2 service2 = new Service2();
@Mock
private SomeDAO someDao;
@Test
public void testMe() {
// substitution
when(someDao.getObj()).thenReturn(new MyObj());
// then I'm calling the outer method
mainService.doMain();
}
}
運行該測試時,我在mainService.doMain()中將NPE設置為null。
在testMe對象service2內是有效的,並且不為null,它已聲明為類變量並已初始化。
我是否誤解了@InjectMock的行為?
Service2
不是注入到MainService
,因為它不是模擬。 因此, mainService
對象的server2
屬性為null
。
您還試圖嘲笑太深。 測試正確的方法MainService
是嘲笑的依賴Service2
,而不是SomeDAO
。
單獨的測試類Service2
是更好的,你嘲笑的依賴SomeDAO
。
public TestClass {
@InjectMocks
private MainService mainService;
@Mock
private Service2 service2;
@Before
public void setUp() {
initMocks(this);
}
@Test
public void testMe() {
mainService.doMain();
verify(service2).doSomethingAnother();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.