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

查看:602
本文介绍了断言在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));
}


推荐答案

关于<$的有趣之处c $ c> 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.

但假设你有一个简单的类,如地址 city street number 并且想断言那些是你期望的那些成为:

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>

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

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