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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With