Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect vs Assert in JUnit or other Java package

Tags:

java

junit

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!!

like image 413
user2183336 Avatar asked Dec 18 '22 13:12

user2183336


1 Answers

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"
like image 125
nickb Avatar answered Jan 01 '23 15:01

nickb