jmeter响应断言_编写自定义的AssertJ断言

本文介绍了如何使用AssertJ库来创建自定义断言,以增强Java项目的测试代码。通过自定义CoffeeAssert类,展示了如何根据业务逻辑验证对象属性,如咖啡的类型和强度。这种方法使得测试更加清晰和易于理解。
摘要由CSDN通过智能技术生成
jmeter响应断言

jmeter响应断言

AssertJ是广泛使用的Hamcrest匹配器的替代匹配库。 实际上,对于我自己的项目,我已经更改为仅使用AssertJ-我只是发现流畅的界面和可扩展性非常吸引人。

您可以编写自定义断言,如下所示:

想象一下一种具有强度和饮料类型的咖啡,例如EspressoLatte 。 定制CoffeeAssert根据其自定义业务逻辑(在本例中为属性)验证咖啡实例。

public class CoffeeAssert extends AbstractAssert<CoffeeAssert, Coffee> {

    public CoffeeAssert(Coffee actual) {
        super(actual, CoffeeAssert.class);
    }

    public static CoffeeAssert assertThat(Coffee actual) {
        return new CoffeeAssert(actual);
    }

    public CoffeeAssert hasType(Coffee.Type type) {
        isNotNull();

        if (actual.getType() != type) {
            failWithMessage("Expected the coffee type to be <%s> but was <%s>", type, actual.getType());
        }

        return this;
    }

    // hasStrength(Strength) omitted ...

    public CoffeeAssert isNotDecaf() {
        isNotNull();

        if (actual.getStrength() == Coffee.Strength.DECAF) {
            failWithMessage("Expected a coffee but got decaf!");
        }

        return this;
    }
}

然后可以使用自定义断言简单地验证咖啡实例。 assertThat的静态导入必须引用CoffeeAssert

import static com.example.coffee.CoffeeAssert.assertThat;
...

Coffee coffee = new Coffee();
coffee.setStrength(Strength.STRONG);
coffee.setType(Type.ESPRESSO);

assertThat(coffee)
    .hasType(Type.ESPRESSO)
    .isNotDecaf();

使用自定义断言可以极大地提高测试代码的质量。

我的时事通讯012中转贴了此帖子

发现帖子有用吗? 订阅我的时事通讯,获取有关IT和Java的更多免费内容,技巧和窍门:

翻译自: https://www.javacodegeeks.com/2018/01/write-custom-assertj-assertions.html

jmeter响应断言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值