Resteasy 服务器端模拟框架
我正在使用 Resteasy 服务器端模拟框架来测试我的服务。我不想测试业务逻辑,但我想测试服务生成的数据。
使用这个方法我能够创建一个简单的测试。然而,在我的 RestEasy 服务中,我有一些我想模拟的依赖项。
请参阅以下我想测试的示例服务。必须模拟协作者,以便可以测试服务。
@Path("v1")
Class ExampleService {
@inject
private Collaborator collaborator;
@GET
@Path("/")
@Produces({ "application/xml", "application/json" })
public Response getDummy() throws WSAccessException, JsonParseException, JsonMappingException, IOException {
...
Result result = collaborator.getResult();
..
return Response.ok("helloworld").build();
}
}
junit 测试如下
@Test
public void testfetchHistory() throws URISyntaxException {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
POJOResourceFactory noDefaults = new POJOResourceFactory(ExampleService.class);
dispatcher.getRegistry().addResourceFactory(noDefaults);
MockHttpRequest request = MockHttpRequest.get("v1/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(..);
}
我如何在测试中模拟协作者?
I am using Resteasy serverside mock framework to test my service. I dont want to test business logic but I would like test the data produced by the service.
Using this approach I am able to create a simple test. However, in my RestEasy service I have a few dependency which I would like to mock.
See the following example service which I would like test. The collaborator must be mocked so the service can be tested.
@Path("v1")
Class ExampleService {
@inject
private Collaborator collaborator;
@GET
@Path("/")
@Produces({ "application/xml", "application/json" })
public Response getDummy() throws WSAccessException, JsonParseException, JsonMappingException, IOException {
...
Result result = collaborator.getResult();
..
return Response.ok("helloworld").build();
}
}
The junit test is the following
@Test
public void testfetchHistory() throws URISyntaxException {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
POJOResourceFactory noDefaults = new POJOResourceFactory(ExampleService.class);
dispatcher.getRegistry().addResourceFactory(noDefaults);
MockHttpRequest request = MockHttpRequest.get("v1/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(..);
}
How can I mock the collaborator in the test?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这对我使用 EasyMock 有用
This worked for me using EasyMock
或者,您可以使用 testfun-JEE 在您的内部运行轻量级 JAX-RS(基于 RESTeasy 和 TJWS)测试并使用 testfun-JEE 的 JaxRsServer junit 规则来构建 REST 请求并断言响应。
testfun-JEE 支持将其他 EJB 以及模拟对象注入到您的 JAX-RS 资源类中。
Alternatively you can use testfun-JEE for running a lightweight JAX-RS (based on RESTeasy and TJWS) inside your test and using testfun-JEE's JaxRsServer junit rule for building REST requests and asserting the responses.
testfun-JEE supports injection of other EJBs as well as mock objects into your JAX-RS resource class.