Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuing test execution in junit4 even when one of the asserts fails

Tags:

java

junit4

I have my existing framework built up using Jfunc which provides a facility to continue exection even when one of the asserts in the test case fails. Jfunc uses junit 3.x framework. But now we are migrating to junit4 so I can't use Jfunc anymore and have replaced it with junit 4.10 jar.
Now the problem is since we have extensively used jfunc in our framework, and with junit 4 we want to make our code continue the execution even when one of the asserts fails in a test case.
Does anyone has any suggestion/idea for this, i know in junit the tests needs to be more atomic i.e. one assert per test case but we can't do that in our framework for some reason.

like image 407
user85 Avatar asked Apr 19 '12 04:04

user85


People also ask

How do you continue the test even if the assert fails?

They don't throw an exception when an assert fails. The execution will continue with the next step after the assert statement. If you need/want to throw an exception (if such occurs) then you need to use assertAll() method as a last statement in the @Test and test suite again continue with next @Test as it is.

What happens when JUnit assertion fails?

The fail assertion fails a test throwing an AssertionError. It can be used to verify that an actual exception is thrown or when we want to make a test failing during its development. In JUnit 5 all JUnit 4 assertion methods are moved to org.

What is use of assert fail method?

The Assert. Fail method provides you with the ability to generate a failure based on tests that are not encapsulated by the other methods.


2 Answers

You can do this using an ErrorCollector rule.

To use it, first add the rule as a field in your test class:

public class MyTest {     @Rule     public ErrorCollector collector = new ErrorCollector();      //...tests... } 

Then replace your asserts with calls to collector.checkThat(...).

e.g.

@Test public void myTest() {     collector.checkThat("a", equalTo("b"));     collector.checkThat(1, equalTo(2)); } 
like image 155
Chris B Avatar answered Sep 22 '22 04:09

Chris B


I use the ErrorCollector too but also use assertThat and place them in a try catch block.

import static org.junit.Assert.*; import static org.hamcrest.Matchers.*;  @Rule public ErrorCollector collector = new ErrorCollector();  @Test public void calculatedValueShouldEqualExpected() {     try {         assertThat(calculatedValue(), is(expected));     } catch (Throwable t) {         collector.addError(t);         // do something     } } 
like image 26
StatusQuo Avatar answered Sep 23 '22 04:09

StatusQuo