Reputation: 123
I'm new to using Mockito for unit-testing Spring Rest controllers. Here is my controller and my test code.
@RestController
@RequestMapping("/api/food/customer")
public class CustomerController {
@Autowired
private CustomerService service;
@RequestMapping(method=RequestMethod.POST, produces= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Customer> addCustomer(@RequestBody Customer c){
Logger log = LoggerFactory.getLogger(CustomerController.class.getName());
try {
service.addCustomer(c);
} catch (UserNameException e){
log.error("UserNameException", e);
return new ResponseEntity(HttpStatus.BAD_REQUEST);
} catch (Exception e){
log.error("", e);
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
log.trace("Customer added: " + c.toString());
return new ResponseEntity(c, HttpStatus.CREATED);
}
}
@RunWith(MockitoJUnitRunner.class)
@WebMvcTest
public class CustomerRestTest {
private MockMvc mockMvc;
@Mock
private CustomerService customerService;
@Mock
private CustomerDao customerDao;
@InjectMocks
private CustomerController customerController;
@Before
public void setup(){
this.mockMvc = MockMvcBuilders.standaloneSetup(customerController).build();
}
@Test
public void testAddDuplicateCustomer() throws Exception {
Customer myCustomer = mock(Customer.class);
when(customerService.addCustomer(myCustomer)).thenThrow(UserNameException.class);
String content = "{\"lastName\" : \"Orr\",\"firstName\" : \"Richard\",\"userName\" : \"Ricky\"}";
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/api/food/customer").accept(MediaType.APPLICATION_JSON).
content(content).contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
}
}
I'm attempting to mock my service layer and have it throw my custom exception when addCustomer is called. I'm getting back HttpStatus.CREATED instead of BAD_REQUEST. What can I do differently with the service mock line (the one with thenThrow) that may work properly?
Upvotes: 1
Views: 5435
Reputation: 6104
I assume this is because you expect a specific customer instance inside your when
clause but this never happens. Spring will deserialize your JSON and will set another customer instance to your method.
Try changing this:
when(customerService.addCustomer(myCustomer)).thenThrow(UserNameException.class);
to this:
when(customerService.addCustomer(any())).thenThrow(UserNameException.class);
Upvotes: 4