java重用不同类中的Junit断言
我有一些测试在JsonObject中进行断言,这些断言针对不同的端点返回,如下所示:
JsonElement product = asJsonObject.get("product");
JsonElement type = product.getAsJsonObject().get("type");
Assert.assertEquals(ProductType.PRODUCT_1.name(), type.getAsString());
JsonElement name = product.getAsJsonObject().get("name");
Assert.assertEquals("name", name.getAsString());
这需要很多Java代码,对吗?有多个端点返回相同的Json,我需要执行相同的断言来保证预期的结果
但我正试图找到一种方法来重用上面的代码。显然,我可以这样做:
new AssertProduct(asJsonObject.get("product")).assert(type, name);
以及:
class AssertProduct {
private JsonElement product;
AssertProduct(JsonElement product) {
this.product = product;
{
boolean assert(String name, String type) {
JsonElement type = product.getAsJsonObject().get("type");
Assert.assertEquals(type, type.getAsString());
JsonElement name = product.getAsJsonObject().get("name");
Assert.assertEquals(name, name.getAsString());
}
}
但是。。。这是解决这类问题的好方法吗
# 1 楼答案
以下是一种基于构建器模式断言json对象预期值的灵活方法:
用法如下所示: