2016-12-14 23 views
1

我有彈簧球衣項目。現在我的測試來自JerseyTest。當我嘗試做在JerseyTest Jersey2.0訪問springbeans

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

更新:在

的src /測試/資源/ META-INF/applicationContext.xml的

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"); 
     } 
    } 
} 

我已經加入豆

<!-- 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"/> 

回答

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"。這告訴我應用程序中有一個陳舊的服務,與注入測試的服務不同。第一個測試雖然工作正常。如果不重新設置,第二個測試也可以正常工作,但是在每個測試中都會留下修改後的服務,這使得測試不是獨立的。

+0

謝謝,但我仍然面臨問題。我在主應用程序中創建了RestTemplate bean,在測試類中我也使用了Restemplate。現在,當我執行測試時,主應用程序中的resttemplate將變爲null,並且無法通過測試進行處理。 – anand

+0

您是否使用'META-INF/applicationContext.xml'而不是我使用的'applicationContext.xml'。我在測試時將類文件放在了類路徑的根目錄下,而不是在'META-INF'中,就像您使用的那樣。 –

+0

是的,我使用了它..我在評論中添加了代碼 – anand

相關問題