使用Jersey2.0访问JerseyTest中的springbeans

时间:2016-12-14 23:52:03

标签: java spring unit-testing jersey-2.0 jersey-test-framework

我有弹簧的球衣项目。现在我的测试来自JerseyTest。我试图做的时候

@AutoWired 
RestTemplate restTemplate;

看起来弹簧在球衣测试中不起作用。我做了一些研究,发现了一些像 spring_jersey 但它没有用,因为我使用的是jersey2.0。

我的代码看起来像

 //AbstractTest 
    package com.test;


            import javax.ws.rs.client.WebTarget;
            import javax.ws.rs.core.Application;

        import org.glassfish.jersey.client.ClientConfig;
        import org.glassfish.jersey.filter.LoggingFilter;
        import org.glassfish.jersey.jackson.JacksonFeature;
        import org.glassfish.jersey.server.ResourceConfig;
        import org.glassfish.jersey.test.JerseyTest;
        import org.glassfish.jersey.server.ServerProperties;
        import org.glassfish.jersey.server.validation.ValidationFeature;

        public abstract class AbstractTest extends JerseyTest
        {
            protected WebTarget getRootTarget(final String rootResource)
            {
                return client().target(getBaseUri()).path(rootResource);
            }

            @Override
            protected final Application configure()
            {
                final ResourceConfig application = configureApplication();

                // needed for json serialization
                application.register(JacksonFeature.class);

                // bean validation
                application.register(ValidationFeature.class);

                // configure spring context
                application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");

                // disable bean validation for tests
                application.property(ServerProperties.BV_FEATURE_DISABLE, "true");

                return application;
            }

            protected abstract ResourceConfig configureApplication();

            @Override
            protected void configureClient(final ClientConfig config)
            {
                // needed for json serialization
                config.register(JacksonFeature.class);

                config.register(new LoggingFilter(java.util.logging.Logger.getLogger(AbstractResourceTest.class.getName()), false));

                super.configureClient(config);
            }
        }



    package com.test;

    import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
    import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
    import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

    //MyTest
        import java.io.FileNotFoundException;
        import java.io.FileReader;
        import java.io.IOException;

    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.Response;

    import org.apache.commons.io.IOUtils;
    import org.glassfish.jersey.server.ResourceConfig;
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.MediaType;
    import org.springframework.test.web.client.MockRestServiceServer;
    import org.springframework.test.web.client.match.MockRestRequestMatchers;
    import org.springframework.web.client.RestTemplate;

    import junit.framework.Assert;

    public final class MyTest extends AbstractTest
        {

        private static final String ROOT_RESOURCE_PATH = "/testUrl";

        @AutoWired
private RestTemplate restTemplate;
        private MockRestServiceServer mockServer;


        @Before
        public void setup(){
            this.restTemplate = new RestTemplate();
            this.mockServer = MockRestServiceServer.createServer(restTemplate);
        }

        @Test
        public void testPostWithString() {

            WebTarget target = getRootTarget(ROOT_RESOURCE_PATH).path("");
            String entityBody = new String();
            entityBody = " My test data";


            final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");


            mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
                    .andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));


            final Response response = target.request().post(entity);
            Assert.assertNotNull("Response must not be null", response.getEntity());
            Assert.assertEquals("Response does not have expected response code", 200, response.getStatus());

            System.out.println("Response = " + response.getEntity());

            String data = response.readEntity(String.class);

            System.out.println("Response = " + data);
            if(response.ok() != null)
            {
                System.out.println("Ok");
            }
        }
    }

更新

public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {
    private static final String ROOT_RESOURCE_PATH = "/test";

    @Override
    public void configureApplication(ResourceConfig config) {
        config.register(MyApp.class);
        config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }

    @Before
    public void setUp() {
        try{
            ((ConfigurableApplicationContext)this.applicationContext).refresh();
            super.setUp();
        }catch(Exception e){

        }
    this.mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Autowired
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Test
    public void doitOnce() {
        WebTarget target = target(ROOT_RESOURCE_PATH);

        String entityBody = new String();

        final javax.ws.rs.client.Entity<String> entity = javax.ws.rs.client.Entity.entity(entityBody, "text/plain");


        mockServer.expect(MockRestRequestMatchers.requestTo(ROOT_RESOURCE_PATH)).andExpect(method(HttpMethod.POST)).andExpect(content().string(entityBody))
                .andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));


        final Response response = target.request().post(entity);


        System.out.println("Response = " + response.getEntity());

        String data = response.readEntity(String.class);

        System.out.println("Response = " + data);
        if(response.ok() != null)
        {
            System.out.println("Ok");
        }
    }
}

我在

中添加了bean
  

的src /测试/资源/ META-INF / applicationContext.xml的

<!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

我在

中添加了相同的bean
  

的src /主/资源/ META-INF / applicationContext.xml的

!-- Our REST Web Service client -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>

1 个答案:

答案 0 :(得分:0)

而不是像这样配置Spring

application.property("contextConfigLocation", "classpath:/META-INF/applicationContext.xml");

您可以改为使用

application.property("contextConfig", <ApplicationContext>);

通过这种方式,您可以拥有ApplicationContext的实例,您可以在其中获取AutowireCapableBeanFactory。有了这个,你可以调用acbf.autowireBean(this)来注入测试类。

这就是我的意思。我测试了它,它可以找到简单的情况。如果您尝试注入不是单身人士的豆子,那么它将会很好地运作,因为新的将为测试而创建,以及您尝试注入的其他地方应用程序代码

public abstract class ApplicationContextAwareJerseyTest extends JerseyTest {

    protected ApplicationContext applicationContext;

    @Override
    protected final ResourceConfig configure() {
        final ResourceConfig config = new ResourceConfig();
        configureApplication(config);

        this.applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        config.property("contextConfig", this.applicationContext);
        final AutowireCapableBeanFactory bf = this.applicationContext.getAutowireCapableBeanFactory();
        bf.autowireBean(this);
        return config;
    }

    public final ApplicationContext getApplicationContext() {
        return this.applicationContext;
    }

    protected void configureApplication(ResourceConfig resourceConfig) {};
}

我不确定的一件事是重置是如何工作的。我试着添加

@Before
public void setUp() throws Exception {
    ((ConfigurableApplicationContext)this.applicationContext).refresh();
    super.setUp();
}

进入抽象类,但似乎没有按预期工作。我使用的测试如下

public class SimpleJerseyTest extends ApplicationContextAwareJerseyTest {


    @Path("test")
    public static class SimpleResource {
        @Autowired
        private MessageService service;

        @GET
        public String getMessage() {
            return this.service.getMessage();
        }
    }

    @Override
    public void configureApplication(ResourceConfig config) {
        config.register(SimpleResource.class);
        config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }

    @Before
    public void before() {
        assertEquals("Hello World", messageService.getMessage());
    }

    @Autowired
    private MessageService messageService;

    @Test
    public void doitOnce() {
        messageService.setMessage("BOOYAH");
        final Response response = target("test").request().get();
        assertEquals("BOOYAH", response.readEntity(String.class));
    }

    @Test
    public void doitTwice() {
        messageService.setMessage("BOOYAH");
        final Response response = target("test").request().get();
        assertEquals("BOOYAH", response.readEntity(String.class));
    }
}

我将为第二次测试得到的结果是服务消息的值是默认消息"Hello World",即使我将消息设置为"BOOYAH"。这告诉我应用程序中存在过时服务,这与注入测试的服务不同。第一次测试工作正常。如果没有重置,第二次测试也可以正常工作,但是每次测试都会留下修改后的服务,这使得测试不是自包含的。