2016-03-02 22 views
1

我使用JAX-RS编写了一个REST Web服务,该服务对我选择的特定JAX-RS实现一无所知。我碰巧使用了TomEE,这意味着我的JAX-RS实现是ApacheCXF。是否有可能编写与您的JAX-RS实现无关的JUnit测试?

我想为Web服务编写单元测试,它对JAX-RS的实现一无所知。这可能吗?到目前为止,我发现的每个示例都涉及使用来自特定JAX-RS实现的类(JAXRSClientFactory for ApacheCXF,Jersey Test Framework等)。

我已经开始尝试使用tomee嵌入式,并且能够测试我的EJB,但它似乎没有启动REST服务。

回答

1

我的解决方案是使用Arquillian与嵌入式TomEE配对。 Arquillian提供了大量的功能,但我只是用它来启动/停止嵌入式TomEE。因此,所有我需要做的是加入到我的pom.xml:

<dependency> 
    <groupId>org.apache.openejb</groupId> 
    <artifactId>arquillian-tomee-embedded</artifactId> 
    <version>${tomee.version}</version> 
    <scope>test</scope> 
</dependency> 

然后,我可以写一个JUnit测试一点点额外的Arquillian的东西,纯JAX-RS:

@RunWith(Arquillian.class) 
public class MyServiceIT { 

    @ArquillianResource 
    private URL webappUrl; 

    @Deployment() 
    public static WebArchive createDeployment() { 
     return ShrinkWrap.create(WebArchive.class) 
      .addClasses(MyService.class) 
      .addAsWebInfResource("META-INF/persistence.xml") //Refers to src/main/resources/META-INF/persistence.xml 
      .addAsWebInfResource("test-resources.xml", "resources.xml") //Refers to src/test/resources/test-resources.xml 
      .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); 
    } 

    @Test 
    public void randomTest() throws URISyntaxException { 
     //Get data from the web service. 
     Client client = ClientBuilder.newClient(); 
     WebTarget webTarget = client.target(webappUrl.toURI().resolve("myentity")); 
     Response response = webTarget.request(MediaType.APPLICATION_JSON).get(); 
     int status = response.getStatus(); 
     List<MyEntity> myEntities = response.readEntity(new GenericType<List<MyEntity>>() {}); 

     //Perform some tests on the data 
    } 
} 
相关问题