Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Failure or Error of Junit Test in @After method

Tags:

java

junit

Is there a way in JUnit to detect within an @After annotated method if there was a test failure or error in the test case?

One ugly solution would be something like that:

boolean withoutFailure = false;  @Test void test() {   ...   asserts...   withoutFailure = true; }  @After public void tearDown() {    if(!withoutFailuere) {       this.dontReuseTestenvironmentForNextTest();    } } 

This is ugly because one need to take care of the "infrastructure" (withoutFailure flag) in the test code.

I hope that there is something where I can get the test status in the @After method!?

like image 371
Ralph Avatar asked Aug 08 '11 12:08

Ralph


People also ask

What does @after do in JUnit?

org.junit Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception.

What does it mean when a JUnit test fails?

Example Failure When writing unit tests with JUnit, there will likely be situations when tests fail. One possibility is that our code does not meet its test criteria. That means one or more test cases fail due to assertions not being fulfilled.

What is the purpose of JUnit @before and @after annotations?

junit Getting started with junit @Before, @After An annotated method with @Before will be executed before every execution of @Test methods. Analogous an @After annotated method gets executed after every @Test method. This can be used to repeatedly set up a Test setting and clean up after every test.


1 Answers

If you are lucky enough to be using JUnit 4.9 or later, TestWatcher will do exactly what you want.

Share and Enjoy!

like image 132
dsaff Avatar answered Sep 21 '22 18:09

dsaff