简体   繁体   中英

Expect vs Assert in JUnit or other Java package

I'm a C++-er doing a bit of Java. In C++'s widely used gtest package there is a distinction between Expectations and 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

An Assert will stop the test if it fails. An Expectation will not stop the test. If an Expectation isn't met the test will fail. The difference is we can see how many Expectations aren't met in a block of code in just one single test run.

Does this have an equivalence in Java? I'm using JUnit currently and seeing Asserts being used everywhere:

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

That's great but the problem is you can't see how many failures you have in one test run!!

For JUnit 4, you can use JUnit's ErrorCollector , like so:

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")));
    }
}

You'll get both failures reported:

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

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

Using JUnit 5 you can use assertAll method and pass your assertions. All assertions will be invoked, test will not stop after the first failing assertion:

@Test
void test() {
    Executable assertion1 = ()  -> Assertions.assertEquals(4, 2);
    Executable assertion2 = ()  -> Assertions.assertEquals(5, 2);
    Assertions.assertAll(assertion1, assertion2);
}

and the message will be:

Multiple Failures (2 failures)
    expected: <4> but was: <2>
    expected: <5> but was: <2>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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