Mockito并期待例外

时间:2016-12-23 14:38:03

标签: java junit mockito junit4

我从我的控制器创建测试,它必须将重定向网址返回到" / register / duplicate"。但是当我执行它时,我得到异常,比如DataIntegrityViolationException。控制器应该捕获此异常,但不捕获

它是如何运作的?我能做什么,对控制器发生了异常并在" catch"中执行代码。原因,将重定向到/注册/复制

测试:

@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();
}

2 个答案:

答案 0 :(得分:0)

要在Mockito中引发异常,您不需要调用真正的方法。您可以使用以下代码:

when(mockService.add(expectedUser)).thenThrow(DataIntegrityViolationException.class)

答案 1 :(得分:0)

如果代码是:

,请尝试简化
try {
    userService.add(new User(username, password));
} catch (DataIntegrityViolationException e) {
    return "redirect:/register/NOT-OK";
}
return "redirect:/register/OK";

你想测试两个分支,然后

@RunWith(MockitoJUnitRunner.class) // for @Mock
class TheTest {

    @Mock
    UserService mockService;

    MockMvc mockMvc;    

    @Before
    public void setup() {        
        RegisterController registerController = new RegisterController(mockService);
        mockMvc = standaloneSetup(registerController).build();
    }

    @Test
    public void testOK() throw Exception {
        // mockService does nothing by default

        mockMvc.perform(post("/register"))
               .andExpect(view().name("/register/OK"));

        Mockito.verify(mockService).add(Matchers.any(User.class));
    }

    @Test
    public void testNotOk() {
        Mockito.when(mockService.add(Matchers.any(User.class))
               .thenThrow(new DataIntegrityViolationException()); // adjust DataIntegrityViolationException constructor args if required.

        // now mockService throw a DataIntegrityViolationException when mockService#add(User) is called

        mockMvc.perform(post("/register"))
               .andExpect(view().name("/register/NOT-OK"));

        Mockito.verify(mockService).add(Matchers.any(User.class));
    }
}