assertAll 与 JUnit5 中的多个断言 [英] assertAll vs multiple assertions in JUnit5

查看:43
本文介绍了assertAll 与 JUnit5 中的多个断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何理由将多个断言分组:

Is there any reason to group multiple assertions:

public void shouldTellIfPrime(){
    Assertions.assertAll(
            () -> assertTrue(isPrime(2)),
            () -> assertFalse(isPrime(4))
    );
}

而不是这样做:

public void shouldTellIfPrime(){
    Assertions.assertTrue(isPrime(2));
    Assertions.assertFalse(isPrime(4));
}

推荐答案

assertAll 的有趣之处在于它始终检查所有通过的断言到它,不管有多少失败.如果一切都通过,一切都很好 - 如果至少有一个失败,你会得到所有出错的详细结果(就这点而言是正确的).

The interesting thing about assertAll is that it always checks all of the assertions that are passed to it, no matter how many fail. If all pass, all is fine - if at least one fails you get a detailed result of all that went wrong (and right for that matter).

它最适合用于断言在概念上属于一起的一组属性.你的第一直觉是我想把它作为一个来断言".

It is best used for asserting a set of properties that belong together conceptionally. Something where your first instinct would be, "I want to assert this as one".

您的具体示例不是 assertAll 的最佳用例,因为使用质数和非质数检查 isPrime 是相互独立的 - 以至于我建议为此编写两个测试方法.

Your specific example is not an optimal use case for assertAll because checking isPrime with a prime and a non-prime is independent of each other - so much so that I would recommend writing two test methods for that.

但是假设你有一个简单的类,比如一个带有 citystreetnumber 字段的地址,并想断言这些就是您希望它们是:

But assume you have a simple class like an address with fields city, street, number and would like to assert that those are what you expect them to be:

Address address = unitUnderTest.methodUnderTest();
assertEquals("Redwood Shores", address.getCity());
assertEquals("Oracle Parkway", address.getStreet());
assertEquals("500", address.getNumber());

现在,一旦第一个断言失败,您将永远看不到第二个断言的结果,这可能很烦人.有很多方法可以解决这个问题,JUnit Jupiter 的 assertAll 就是其中之一:

Now, as soon as the first assertion fails, you will never see the results of the second, which can be quite annoying. There are many ways around this and JUnit Jupiter's assertAll is one of them:

Address address = unitUnderTest.methodUnderTest();
assertAll("Should return address of Oracle's headquarter",
    () -> assertEquals("Redwood Shores", address.getCity()),
    () -> assertEquals("Oracle Parkway", address.getStreet()),
    () -> assertEquals("500", address.getNumber())
);

如果被测方法返回错误的地址,这就是你得到的错误:

If the method under test returns the wrong address, this is the error you get:

org.opentest4j.MultipleFailuresError:
    Should return address of Oracle's headquarter (3 failures)
    expected: <Redwood Shores> but was: <Walldorf>
    expected: <Oracle Parkway> but was: <Dietmar-Hopp-Allee>
    expected: <500> but was: <16>

这篇关于assertAll 与 JUnit5 中的多个断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆