泽西岛 - 如何模拟服务 [英] Jersey - How to mock service

查看:145
本文介绍了泽西岛 - 如何模拟服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Jersey测试框架对我的网络服务进行单元测试。

I am using "Jersey Test Framework" for unit testing my webservice.

这是我的资源类:

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

// The Java class will be hosted at the URI path "/helloworld" 

@Path("/helloworld") 
public class class HelloWorldResource {

    private SomeService service;

    @GET 
    @Produces("text/plain")
    public String getClichedMessage() {
        // Return some cliched textual content
        String responseFromSomeService = service.getSomething();
        return responseFromSomeService;
    }
}

如何在单元测试中模拟SomeService?

How can I mock SomeService in unit tests ?

推荐答案

请参阅下面的更新:您不需要工厂

See Update below: You don't need a Factory

如果您使用的是泽西2,则一种解决方案是使用 HK2 - 与Jersey dist一起提供)。当然,还需要一个Mocking框架。我将使用Mockito。

If you are using Jersey 2, one solution would be to use Custom Injection and Lifecycle Management feature (with HK2 - which comes with the Jersey dist). Also required would be a Mocking framework of course. I'm going to use Mockito.

首先使用模拟实例创建一个Factory:

First create a Factory with mocked instance:

public static interface GreetingService {
    public String getGreeting(String name);
}

public static class MockGreetingServiceFactory 
                                     implements Factory<GreetingService> {
    @Override
    public GreetingService provide() {
        final GreetingService mockedService
                = Mockito.mock(GreetingService.class);
        Mockito.when(mockedService.getGreeting(Mockito.anyString()))
                .thenAnswer(new Answer<String>() {
                    @Override
                    public String answer(InvocationOnMock invocation) 
                                                      throws Throwable {
                        String name = (String)invocation.getArguments()[0];
                        return "Hello " + name;
                    }

                });
        return mockedService;
    }

    @Override
    public void dispose(GreetingService t) {}
}

然后使用 AbstractBinder 将工厂绑定到接口/服务类,并注册绑定器。 (这些都在上面的链接中描述):

Then use the AbstractBinder to bind the factory to the interface/service class, and register the binder. (It's all described in the link above):

@Override
public Application configure() {
    AbstractBinder binder = new AbstractBinder() {
        @Override
        protected void configure() {
            bindFactory(MockGreetingServiceFactory.class)
                               .to(GreetingService.class);
        }
    };
    ResourceConfig config = new ResourceConfig(GreetingResource.class);
    config.register(binder);
    return config;
}

看起来很多,但它只是一个选项。我不太熟悉测试框架,或者它是否具有注射的模拟功能。

Seems like a lot, but it's just an option. I'm not too familiar with the test framework, or if it has an mocking capabilities for injection.

这是完整的测试:

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class ServiceMockingTest extends JerseyTest {

    @Path("/greeting")
    public static class GreetingResource {

        @Inject
        private GreetingService greetingService;

        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String getGreeting(@QueryParam("name") String name) {
            return greetingService.getGreeting(name);
        }
    }

    public static interface GreetingService {
        public String getGreeting(String name);
    }

    public static class MockGreetingServiceFactory 
                                  implements Factory<GreetingService> {
        @Override
        public GreetingService provide() {
            final GreetingService mockedService
                    = Mockito.mock(GreetingService.class);
            Mockito.when(mockedService.getGreeting(Mockito.anyString()))
                    .thenAnswer(new Answer<String>() {
                        @Override
                        public String answer(InvocationOnMock invocation) 
                                                       throws Throwable {
                            String name = (String)invocation.getArguments()[0];
                            return "Hello " + name;
                        }

                    });
            return mockedService;
        }

        @Override
        public void dispose(GreetingService t) {}
    }

    @Override
    public Application configure() {
        AbstractBinder binder = new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(MockGreetingServiceFactory.class)
                        .to(GreetingService.class);
            }
        };
        ResourceConfig config = new ResourceConfig(GreetingResource.class);
        config.register(binder);
        return config;
    }

    @Test
    public void testMockedGreetingService() {
        Client client = ClientBuilder.newClient();
        Response response = client.target("http://localhost:9998/greeting")
                .queryParam("name", "peeskillet")
                .request(MediaType.TEXT_PLAIN).get();
        Assert.assertEquals(200, response.getStatus());

        String msg = response.readEntity(String.class);
        Assert.assertEquals("Hello peeskillet", msg);
        System.out.println("Message: " + msg);

        response.close();
        client.close();

    }
}

此测试的依赖关系:

<dependency>
    <groupId>org.glassfish.jersey.test-framework.providers</groupId>
    <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
    <version>2.13</version>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.9.0</version>
</dependency>






更新



所以在大多数情况下,你真的不需要 Factory 。您可以简单地将模拟实例与其合约绑定:


UPDATE

So in most cases, you really don't need a Factory. You can simply bind the mock instance with its contract:

@Mock
private Service service;

@Override
public ResourceConfig configure() {
    MockitoAnnotations.initMocks(this);
    return new ResourceConfig()
        .register(MyResource.class)
        .register(new AbstractBinder() {
            @Override
            protected configure() {
                bind(service).to(Service.class);
            }
        });
}

@Test
public void test() {
    when(service.getSomething()).thenReturn("Something");
    // test
}

更简单!

这篇关于泽西岛 - 如何模拟服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆