简体   繁体   English

如何使用MockRestServiceServer在RESTful控制器中引发IllegalArgumentException异常的测试

[英]How to test than an IllegalArgumentException is thrown in a RESTful controller using MockRestServiceServer

I have a very simple RESTful controller that produces a json and I want to test if it works ok. 我有一个非常简单的RESTful控制器,它产生一个json,我想测试一下是否正常。 I can easily test the method when the user id exists, no problem with that. 当用户ID存在时,我可以轻松测试该方法,这没有问题。 I would like to validate that an IllegalArgumentException is thrown when the given id does not exist. 我想验证当给定的id不存在时抛出IllegalArgumentException。 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? 如果我使用response(withStatus(HttpStatus.NOT_FOUND),我既不验证异常也不验证我的消息。有人可以帮我吗?

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: 这是具有有效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 问候,丹妮拉

为什么不捕获异常并创建日志并将异常写入日志。

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. 请注意expected的附加参数,该参数指定在执行测试时必须抛出的异常。

Additionally to assert the exception message, error code etc. create a custom exception matcher. 此外,要声明异常消息,错误代码等,请创建自定义异常匹配器。 Refer my answer for details and pseudo code. 请参阅我的答案以获取详细信息和伪代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM