【问题标题】:Reuse Junit asserts in different classes在不同的类中重用 Junit 断言
【发布时间】:2017-05-30 13:12:46
【问题描述】:

我有一些测试在 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());
    }

}

但是……这是解决这类问题的好方法吗?

【问题讨论】:

  • 我会把它们分开,这样你就可以做到AssertProduct(asJsonObject.get("product")).ofType(x).ofName(y)
  • 恕我直言,这是一个好方法。
  • @vikingsteve 不错。你介意用这个建议来回答吗?我会将问题标记为已解决。

标签: java junit reusability


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

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 2018-12-23
    • 2018-06-18
    • 2023-03-15
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多