有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    以下是一种基于构建器模式断言json对象预期值的灵活方法:

    public class AssertProduct {
    
        private JsonElement product;
    
        public AssertProduct(JsonElement product) {
            this.product = product;
        }
    
        public static AssertProduct withProduct(JsonElement product) {
            return new AssertProduct(product);
        }
    
        AssertProduct ofName(String name) {
            Assert.assertEquals(name, product.getAsJsonObject().get("name").getAsString());
            return this;
        }
    
        AssertProduct ofType(String type) {
            Assert.assertEquals(type, product.getAsJsonObject().get("type").getAsString());
            return this;
        }
    }
    

    用法如下所示:

    AssertProduct.withProduct(checkMe).ofName("some-name").ofType("some-type");