【问题标题】:Access springbeans in JerseyTest with Jersey2.0使用 Jersey2.0 在 JerseyTest 中访问 springbeans
【发布时间】:2016-12-14 23:52:03
【问题描述】:

我有春天的球衣项目。现在我的测试是从 JerseyTest 派生的。当我尝试做时

@AutoWired 
RestTemplate restTemplate;

看起来 spring 在球衣测试中不起作用。我做了一些研究,发现了一些链接,比如 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/test/resources/META-INF/applicationContext.xml

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

我在

中添加了相同的 bean

src/main/resources/META-INF/applicationContext.xml

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

【问题讨论】:

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


    【解决方案1】:

    而不是像这样配置Spring

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

    你可以改用

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

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

    这就是我的意思。我测试了它,它适用于简单的情况。如果您尝试注入的bean 不是单例,则不会很好地工作,因为将为测试以及您尝试在应用程序代码中注入的任何其他位置创建新的 p>

    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"。这告诉我应用程序中有一个陈旧的服务,这与注入测试的服务不同。第一个测试工作正常。如果不重置,第二个测试也可以正常工作,但是在每个测试中都会留下修改后的服务,这使得测试不是独立的。

    【讨论】:

    • 谢谢,但我仍然面临问题。我在主应用程序中创建了 RestTemplate bean,在测试类中我也在使用 Restemplate。现在,当我在主应用程序中执行测试时,resttemplate 为空,无法进行测试。
    • 你用的是META-INF/applicationContext.xml,而不是我用的applicationContext.xml。我在测试时将文件放在类路径的根目录中,而不是像您拥有的那样在 META-INF
    • 给我几分钟。我会将完整的 repo 发布到 github。
    • 我的应用程序是一个调用休息端点的休息客户端。我正在测试它,所以我们可以在主应用程序中使用 MockRestServiceServer 模拟 resttemplate
    • 我不认为我完全理解 MockRestServiceService 的用途,但here is what I used to test
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多