JUnit或其他Java包中Expect与Assert的区别

4

我是一名擅长C++的程序员,现在在学习Java。在广泛使用的C++测试框架gtest中,Expectations和Assertions有所区别:

 EXPECT_EQ(4, 2); // will ultimately cause test failure but test continues to run
 ASSERT_EQ(4, 2); // test will stop here and fail

断言会在失败时停止测试,期望则不会。如果未满足期望,则测试将失败。区别在于我们可以在一个测试运行中看到多少期望没有被满足。

Java中是否有相应的功能?我目前正在使用JUnit并看到到处都在使用Asserts:

Assert.assertEquals(4, 2); // just like C++, this stops the show

这很好,但问题是您无法看到在一个测试运行中有多少个失败!


请参见 https://stackoverflow.com/questions/26366274/junit-multiple-results-in-one-test。 - user
2个回答

6

对于JUnit 4,您可以使用JUnit的ErrorCollector,如下所示:

public class TestClass {
    @Rule
    public ErrorCollector collector = new ErrorCollector();

    @Test
    public void test() {
        collector.checkThat(4, is(equalTo(5)));
        collector.checkThat("foo" , is(equalTo("bar")));
    }
}

您将会得到两种错误报告:

java.lang.AssertionError: 
Expected: is <5>
     but: was <4>

java.lang.AssertionError: 
Expected: is "bar"
     but: was "foo"

5
使用JUnit 5,您可以使用assertAll方法并传递您的断言。所有断言都将被调用,测试不会在第一个失败的断言后停止:
@Test
void test() {
    Executable assertion1 = ()  -> Assertions.assertEquals(4, 2);
    Executable assertion2 = ()  -> Assertions.assertEquals(5, 2);
    Assertions.assertAll(assertion1, assertion2);
}

并且消息将会是:
Multiple Failures (2 failures)
    expected: <4> but was: <2>
    expected: <5> but was: <2>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接