java 泽西岛-如何模拟服务

vkc1a9a2  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(159)

我正在使用“Jersey测试框架”对我的Web服务进行单元测试。
下面是我的资源类:

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?

lrl1mhuk

lrl1mhuk1#

请参阅以下更新:您不需要Factory

如果您使用的是Jersey 2,一个解决方案是使用Custom Injection and Lifecycle Management功能(使用HK2-Jersey dist附带的)。当然,还需要一个Mocking框架。我要用莫奇托。
首先创建一个带有模拟示例的Factory:

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将工厂绑定到接口/服务类,并注册绑定器。(以上链接都有介绍):

@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;
}

看起来很多,但这只是一个选择。我不太熟悉这个测试框架,或者它是否有模拟注入的能力。
以下是完整的测试:

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。您可以简单地将mock示例与其合约绑定:

@Mock
private Service service;

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

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

简单多了!

46qrfjad

46qrfjad2#

下面是我如何使用Jersey 2.20,Spring 4.1.4 Release,Mockito 1.10.8和TestNG 6.8.8完成的。

@Test
public class CasesResourceTest extends JerseyTestNg.ContainerPerMethodTest {

    @Mock
    private CaseService caseService;

    @Mock
    private CaseConverter caseConverter;    

    @Mock
    private CaseRepository caseRepository;

    private CasesResource casesResource;

    @Override
    protected Application configure() {

        MockitoAnnotations.initMocks(this);
        casesResource = new CasesResource();

        AbstractBinder binder = new AbstractBinder() {

            @Override
            protected void configure() {
                bindFactory(new InstanceFactory<CaseConverter>(caseConverter)).to(CaseConverter.class);
                bindFactory(new InstanceFactory<CaseService>(caseService)).to(CaseService.class);
            }
        };

        return new ResourceConfig()
            .register(binder)
            .register(casesResource)
            .property("contextConfigLocation", "solve-scm-rest/test-context.xml");
    }

    public void getAllCases() throws Exception {

        when(caseService.getAll()).thenReturn(Lists.newArrayList(new solve.scm.domain.Case()));
        when(caseConverter.convertToApi(any(solve.scm.domain.Case.class))).thenReturn(new Case());

        Collection<Case> cases = target("/cases").request().get(new GenericType<Collection<Case>>(){});

        verify(caseService, times(1)).getAll();
        verify(caseConverter, times(1)).convertToApi(any(solve.scm.domain.Case.class));

        assertThat(cases).hasSize(1);
    }
}

你还需要这个类,它使上面的绑定代码更容易一些:

public class InstanceFactory<T> implements Factory<T> {

    private T instance;

    public InstanceFactory(T instance) {
        this.instance = instance;
    }

    @Override
    public void dispose(T t) {
    }

    @Override
    public T provide() {
        return instance;
    }

}

编辑为pr下面是我的test-context.xml的内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

事实证明,我的test-context.xml既没有示例化任何bean,也没有扫描任何包,事实上,它根本没有做任何事情。我想我只是把它放在那里,以防我可能需要它。

相关问题