简体   繁体   English

每次测试可以有多个断言吗?

[英]Can there be multiple asserts per one test?

I started looking at FsCheck yesterday, and I am trying to write a simple test, that any instance of DiscountAmount will always have negative value. 我昨天开始关注FsCheck,我正在尝试编写一个简单的测试,任何DiscountAmount实例都会有负值。 My question is, is it ok to have multiple asserts within one test. 我的问题是,在一次测试中有多个断言是否可以。 For example, here I am saying that amount from which discountAmount has been created plus discount amount should be 0. But I also say that discount amount should be less than 0. Should this be 2 tests or 1? 例如,我在这里说,创建discountAmount的金额加上折扣金额应为0.但我也说折扣金额应该小于0.这应该是2次测试还是1次?

    public class DiscountAmountTests
    {
        [Property()]
        public void value_or_created_discountAmount_should_be_negative()
        {
            Arb.Register<AmountArbitrary>();
            Prop.ForAll<Amount>(
                v =>
                {
                    var sut = new DiscountAmount(v);
                    var expectedResult = 0;
                    var result = v + sut;

                    result.Should().Be(expectedResult);

                    sut.Value.Should().BeLessThan(0);

                })
                .QuickCheckThrowOnFailure();
        }

        public class AmountArbitrary
        {
            public static Arbitrary<Amount> Amounts()
            {
                return Arb.Generate<decimal>().Where(x => x > 0)
                    .Select(x => new Amount(x))
                    .ToArbitrary();
            }
        }

    }
}

I would say this is really up to you. 我会说这真的取决于你。 I think there are arguments pro and cons - on the one hand, sometimes setup cost is expensive (be it in terms of programmer work to get the system into a particular state, or really compute resource cost, eg you have to do a expensive query to the DB or something) and then in my opinion it's worth making tests more coarsely grained. 我认为有正面和缺点的论据 - 一方面,有时设置成本昂贵(无论是程序员工作使系统进入特定状态,还是真正计算资源成本,例如你必须做一个昂贵的查询到DB或其他东西)然后在我看来,值得进行更细粒度的测试。

The trade-off is that it's typically less clear what the problem is if a coarse grained test fails. 权衡的是,如果粗粒度测试失败,通常不太清楚问题是什么。

In comparison with unit tests, FsCheck has a bit more setup costs in terms of argument generation, and it is attractive to make FsCheck tests more coarse-grained than unit tests. 与单元测试相比,FsCheck在参数生成方面具有更多的设置成本,并且使FsCheck测试比单元测试更粗糙是有吸引力的。 Also note that FsCheck has some methods like Label , And . 另请注意,FsCheck有一些方法,如LabelAnd Or to combine different properties together while sharing the argument generation, and still allow you to see what part of your test fails, somewhat off-setting one downside. Or在共享参数生成的同时将不同的属性组合在一起,并且仍然允许您查看测试的哪个部分失败,稍微偏离了一个缺点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM