【发布时间】:2016-12-23 14:38:02
【问题描述】:
我从我的控制器创建测试,它必须将重定向 url 返回到“/register/duplicate”。但是当我执行该操作时,我会遇到异常,例如 DataIntegrityViolationException。控制器应该捕捉到这个异常,但没有捕捉到
它是如何工作的?我能做的,对控制器来说,发生了一个异常并以“catch”原因执行代码,将重定向到/register/duplicate
测试:
@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 让一些 mock 抛出异常??
-
连我都答不上来。
-
@RC。是的,有些人喜欢这样。我想,当执行方法
userService.add()时,抛出异常,它在catch casecatch (DataIntegrityViolationException e) {...}中捕获这个异常