【问题标题】:Is it possible to write JUnit tests that are agnostic to your JAX-RS implementation?是否可以编写与您的 JAX-RS 实现无关的 JUnit 测试?
【发布时间】:2016-03-02 22:13:46
【问题描述】:

我使用 JAX-RS 编写了一个 REST Web 服务,它对我选择的特定 JAX-RS 实现一无所知。我碰巧在使用 TomEE,这意味着我的 JAX-RS 实现是 ApacheCXF。

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

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

【问题讨论】:

    标签: rest junit jax-rs


    【解决方案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>
    

    然后我可以用一些额外的 Arquillian 东西和简单的 JAX-RS 编写一个 JUnit 测试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多