我从我的控制器创建测试,它必须将重定向url返回到“/ register/duplicate”。但是当我执行该操作时,我会遇到异常,例如DataIntegrityViolationException。控制器应该抓住这个例外,但不抓住Mockito和预计的例外
它是如何工作的?而我能做些什么,到控制器的异常已经发生,并且在“捕获”事业执行代码,将被重定向到/注册/复制
测试:
@Test
public void testRegisterPageLogic_Duplicate() throws Exception {
expectedUser = new User("Jorg", "Brush");
UserService mockService = mock(UserService.class);
userService.add(expectedUser);
when(mockService.add(expectedUser)).thenCallRealMethod();
registerController = new RegisterController(mockService);
mockMvc = standaloneSetup(registerController).build();
mockMvc.perform(post("/register")
.param("hide", "up")
.param("username", expectedUser.getUsername())
.param("password", expectedUser.getPassword()))
.andExpect(redirectedUrl("/register/duplicate"));
Mockito.verify(mockService, atLeastOnce()).add(expectedUser);
userService.remove(userService.findUser("Jorg").getUserId());
}
控制器的方法:
@RequestMapping(method = POST)
public String register(@RequestParam("hide") String hide,
@RequestParam("username") String username,
@RequestParam("password") String password) {
if (hide.equals("up")) {
try {
userService.add(new User(username, password));
} catch (DataIntegrityViolationException e) {
return "redirect:/register/duplicate";
}
}
User user = userService.findUser(username);
if (user == null) {
return "redirect:/register/notExists";
}
UserSession.setUser(user);
UserSession.setId(user.getUserId());
return "redirect:/notes/" + UserSession.getUser().getUsername();
}
我已阅读你的问题两次,对不起,我不明白你想要什么 –
你问如何使用mockito使一些模拟抛出异常? –
即使我不明白这个问题。 –