Alex2330
Alex2330

Reputation: 347

Mockito Expect an Exception

I'm trying to test the method below with Mockito and Junit:

@Transactional
@RequestMapping(method=RequestMethod.PUT,value ="/updateEmployer/{empId}")
public @ResponseBody Object updateEmployer(@PathVariable Integer empId,) throws Exception {

    Employee e = EmployeeRepository.findOne(empId);

    for (Department de : e.getDepartement()){
        de.setDepartmentName(e.getName + "_" + de.getName());       
    }
    EmployeeRepository..saveAndFlush(e);
    return null;
}   

This is the method Test:

@Test  // throw java.lang.NullPointerException
 public void updateEmployeeFailureTest() throws Exception {

        mockMvc.perform(
            MockMvcRequestBuilders
                    .put("/updateEmployer/{empId}",18)                      
                    .accept(MediaType.APPLICATION_JSON)).andDo(print())         

              .andExpect(MockMvcResultMatchers.view().name("errorPage"))
               .andExpect(MockMvcResultMatchers.model().attributeExists("exception"))
              .andExpect(MockMvcResultMatchers.forwardedUrl("/WEB-INF/jsp/errorPage.jsp"))
              .andExpect(MockMvcResultMatchers.status().isInternalServerError());       

    }   

The printstack:

 MockHttpServletRequest:
     HTTP Method = PUT
     Request URI = /updateEmployer/18
      Parameters = {}
         Headers = {Content-Type=[application/json], Accept=   application/json]}

         Handler:
            Type = com.controllers.employeeController
          Method = public java.lang.Object    com.controllers.employeeController.updateEmployer(java.lang.Integer) throws   java.lang.Exception

           Async:
      Was async started = false
      Async result = null

    Resolved Exception:
            ***Type = java.lang.NullPointerException***

    ModelAndView:
       View name = errorPage
            View = null
       Attribute = exception
           ***value = java.lang.NullPointerException***

         FlashMap:

  MockHttpServletResponse:
          Status = 500
   Error message = null
         Headers = {}
    Content type = null
            Body = 
   Forwarded URL = /WEB-INF/jsp/errorPage.jsp
  Redirected URL = null
         Cookies = []

It's work but when i try to catch the text or the exception throwed by this method
adding @Test (expected= java.lang.NullPointerException.class) i have this error:

java.lang.AssertionError: Expected exception: java.lang.NullPointerException

when i try to get the nullPointerException Text as a value of the attribute (exception) of the section ModelAndView i get this error:

java.lang.AssertionError: Model attribute 'exception' expected:java.lang.NullPointerException but was:java.lang.NullPointerException

Is there a way to expect the exception throwed or the text in the value attribut ( value = java.lang.NullPointerException) or the Text in the Resolved Exception section using mockito (mockmvc)?

Any help will be much appreciated

Upvotes: 2

Views: 4906

Answers (2)

Rogério Ramos
Rogério Ramos

Reputation: 99

A simpler solution would be to catch the exception through the MvcResult, like this:

...
MvcResult result = mockMvc.perform(...)
        ...
        ...
        .andReturn();

assertThat(result.getResolvedException(), instanceOf(YourException.class));
assertThat(result.getResolvedException().getMessage(), is("Your exception message");
...

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691605

You need to test that the exception attribute of the model is an instance of NullPointerException.

This can be done using a Hamcrest matcher:

 .andExpect(MockMvcResultMatchers.model().attribute(
     "exception", 
      Matchers.isA(NullPointerException.class))

Upvotes: 1

Related Questions