我是 JUnit 的初学者。我想创建一个测试以获取所有 product
s 并通过 id
--- 获取 product
s。这是我的 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);
}
}
原文由 CooperShelly 发布,翻译遵循 CC BY-SA 4.0 许可协议
假设您想要进行单元测试,而不是集成、功能或其他类型的测试,您应该简单地实例化
ProduitResource
并对其运行测试:这样做可能需要模拟环境,在您的情况下,您可能需要模拟从中获取的任何
Produit
。如果您真的向它发出 HTTP 请求,这将需要运行服务器并且不再构成单元测试(因为您要测试的不仅仅是该单元自身的功能)。为此,您可以让您的构建工具在运行测试之前启动服务器(例如,可以在此处使用 Jetty Maven 插件 在
pre-integration-test
阶段启动 Jetty),或者您可以让 JUnit 在一个准备步骤 (@BeforeClass
) 如此 处 所述。关闭服务器的类似逻辑(在 Maven 中使用post-integration-test
阶段或在 JUnit 中使用@AfterClass
)。有很多库可以帮助您编写 RESTful 资源的实际测试, 放心 是一个好的库。