Spring mvc 从父类模拟方法
我有以下几节课:Spring mvc 从父类模拟方法,spring-mvc,mocking,mockito,junit4,spring-test,Spring Mvc,Mocking,Mockito,Junit4,Spring Test,我有以下几节课: public class ControllerA { @Autowired private UserService userService; protected void methodControllerA() { userService.findAll(); .... } } public class ControllerB extends ControllerA { @Autowired
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时,我会得到一个空指针,但是如果我不实例化ControllerB(),我就不能覆盖methodControllerA(),所以我会在这个方法内的Userservice中得到一个空指针。。。
有什么想法吗?谢谢解决了
AccountServiceImp accountService = mock(AccountServiceImp.class);
controller = new ControllerB() {
protected void methodControllerA() {
}
};
controller.setAccountService(accountService);
controller.methodControllerB();
如何实例化accountService/UserService?有设置器或构造函数吗?我忘了代码中的@Autowired。EditedSpringApplicationContext将在测试中注入这两个类,您在哪里创建?通过@ContextConfiguration,我刚刚更新了代码