如何为REST Web服务创建JUnit测试?

时间:2016-09-15 14:07:22

标签: java web-services rest testing junit

我是JUnit的初学者。 我想创建一个测试来获取所有product并通过product获取id。 这是我的Java代码:

@Path("/produits")
@Produces("application/json")
public class ProduitResource {

    public ProduitResource() {
    }

    @GET
    public List<Produit> getProduits() {
        System.out.println("getProduits");

        return ReadXMLFile.getProduits();
    }

    @GET
    @Path("numProduit-{id}")
    public Produit getProduit(@PathParam("id") String numProduit) {
        System.out.println("getProduit");

        for (Produit current : ReadXMLFile.getProduits()) {
            if (numProduit.equals(current.getNumProduit())) {
                return current;
            }
        }
        return null;
    }

    @GET
    @Path("/search")
    public List<Produit> searchProduitsByCriteria(@QueryParam("departure") String departure, @QueryParam("arrival") String arrival, @QueryParam("arrivalhour") String arrivalHour) {
        System.out.println("searchProduitsByCriteria");

        return ReadXMLFile.getProduits().subList(0, 2);
    }
}

3 个答案:

答案 0 :(得分:6)

假设你想要的是进行单元测试,而不是集成,功能或其他类型的测试,你应该简单地实例化ProduitResource并对其进行测试:

@Test
public void testFetchingById() {
   ProduitResource repo = new ProduitResource();
   Produit prod = repo.getProduit("prod123");
   assertNotNull(prod);
   assertEquals(prod.getId(), "prod123");
}

执行此操作可能需要模拟环境,在您的情况下,您可能需要模拟从Produit获取的任何内容。

如果您要实际触发HTTP请求,则需要运行服务器并且不再构成单元测试(因为您不仅仅测试此单元自身的功能)。要做到这一点,你可以让你的构建工具在运行测试之前启动服务器(例如Jetty Maven plugin可以用来在pre-integration-test阶段启动Jetty),或者你可以让JUnit在准备步骤(@BeforeClass),如here所述。关闭服务器的类似逻辑(在Maven中使用post-integration-test阶段或在JUnit中使用@AfterClass

有许多库可以帮助您编写RESTful资源的实际测试,rest-assured是一个很好的资源。

答案 1 :(得分:0)

您可以使用两种基本策略(并且您可能希望同时执行这两种操作)。

  1. 重新设计Web服务的代码,以便模拟与环境交互的任何对象的依赖关系,例如示例中的ReadXMLFile。模拟对象将返回固定数据,而不是读取任何文件或数据库。使用像Mockito这样的模拟框架可以减少模拟对象的创建。然后,您可以在JUnit测试中实例化ProductResource类,并像任何其他Java代码一样调用它。

  2. 创建JUnit设置和拆除方法(使用@ Before,@ BeforeClass,@ AfterTemp和@AfterClass注释),这些方法将设置测试环境,种子数据并部署应用程序并在清理时进行清理测试结束了。然后使用REST客户端API(例如Jersey客户端API或Spring RestTemplate)来调用您的Web服务并获取结果。

答案 2 :(得分:0)

正如kaqqao所提到的,您可以简单地实例化ProduitResource并对其进行测试,但在这种情况下,您无法进行HTTP调用,请检查HTTP状态。 REST Assured 适用于测试REST服务,但问题是您需要将其作为单独的实例运行,这不方便 - RestAssured testing without running Tomcat。另一种选择是使用Jersey Test(How to in-memory unit test Spring-Jersey),它提供在内存中测试REST服务的能力。

相关问题