我有几个课程如下:
public class ControllerA {
@Autowired
private UserService userService;
protected void methodControllerA() {
userService.findAll();
....
}
}
public class ControllerB extends ControllerA {
@Autowired
private AccountService accountService;
public void methodControllerB() {
accountService.findAll();
methodControllerA();
}
}
我想测试 ControllerB.methodControllerB()的行为,所以我按如下方式创建了Junit类:
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = {
"classpath:services/testServiceContext.xml",
"classpath:apply/applyController.xml",
"classpath:testApplicationContext.xml",
"classpath:testDatabaseMessageSource.xml",
"classpath:controller/propertyeditors/propertyeditorsContext.xml"})
public class ControllerBTest {
@Mock
private AccountService accountService;
@InjectMocks
private ControllerB controller;
@Test
public void methodControllerBTest() throws Exception {
controller = new ControllerB() {
protected void methodControllerA() {
}
};
controller.methodControllerB();
asserts();
}
}
当然,当我实例化ControllerB()时,accountService没有被模拟,所以当调用accountService时我得到一个nullpointer,但如果我没有实例化ControllerB(),我就不能覆盖methodControllerA() ,所以我在这个方法里面的Userservice中得到了一个nullpointer ... 有任何想法吗 ?感谢
答案 0 :(得分:0)
解决了!
AccountServiceImp accountService = mock(AccountServiceImp.class);
controller = new ControllerB() {
protected void methodControllerA() {
}
};
controller.setAccountService(accountService);
controller.methodControllerB();