我從我的控制器創建測試,它必須將重定向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使一些模擬拋出異常? –
即使我不明白這個問題。 –