0

I have a very simple RESTful controller that produces a json and I want to test if it works ok. I can easily test the method when the user id exists, no problem with that. I would like to validate that an IllegalArgumentException is thrown when the given id does not exist. Is there any way to do that?

In the application, when an assertion error occurs, the response is redirected to a generic error page that displays a generic message. If I use response(withStatus(HttpStatus.NOT_FOUND) I'm not validating the exception nor my message. Can somebody help me please?

This is the method I want to test:

@Transactional (readOnly = true)
@RequestMapping(method=RequestMethod.GET, value="/json/user/{id}",  headers="Accept=application/json, text/html")
public @ResponseBody UserData getUserJson(@PathVariable Long id)
{
    User user = this.userService.findUserById(id);
    Assert.notNull(user , "User does not exist with the given id: " + id);
    return new UserData (user);
}

This is a test with a valid id:

@Test
public void testRestUserJson() {

mockServer.expect(requestTo(JSON_URL + USER)).andExpect(method(HttpMethod.GET))
          .andRespond(withSuccess(JSON_RESPONSE, MediaType.APPLICATION_JSON));


UserData userData = restClientTemplate.getForObject(JSON_URL + USER, UserData.class);
AssertResponseContent(userData , expectedData);

mockServer.verify();
EasyMock.verify(user);
}

Regards, Daniela

Daniela
  • 318
  • 3
  • 12

2 Answers2

0

Why don't you catch the exceptions and create a log and write the exception to log.

neo
  • 1,952
  • 2
  • 19
  • 39
  • I'm forced to add a Response when using MockRestServiceServer: mockServer.expect("something").andRespond("something"). I cannot just catch the exception because I will receive the response set in the method and that method does not accept exceptions classes... – Daniela Nov 17 '14 at 01:46
0

Update your test as below.

@Test(expected = IllegalArgumentException.class)
public void testRestUserJson() { ... }

Note the additional parameter expected which specify the Exception which must be thrown while test execution.

Additionally to assert the exception message, error code etc. create a custom exception matcher. Refer my answer for details and pseudo code.

Bond - Java Bond
  • 3,972
  • 6
  • 36
  • 59
  • The problem that I have is that I don't know what to put in the response of the mock server in order to responde with an exception. mockServer.expect(requestTo(JSON_URL + USER)).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess(JSON_RESPONSE, MediaType.APPLICATION_JSON)); I cannot mock a request without a response and if instead of using a successful response I use and invalid one, or an error, I will get that exception instead of the IllegalArgument one. – Daniela Nov 17 '14 at 20:17