Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different teardown for each @Test in jUnit

Tags:

java

junit

junit4

Is there way to define a different teardown for each @Test in jUnit?

like image 565
Daniel Avatar asked Jul 26 '11 12:07

Daniel


People also ask

What is tearDown () method called in JUnit?

When is the tearDown() method called in JUnit? Explanation: The tearDown() method is called after the execution of every @Test method.

Does tearDown run after every test?

Yes, it is called after each testXXX method.

What is @test annotation in JUnit?

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure.

Is JUnit setUp called for each test?

First, JUnit 4 has a setup method that is invoked before each test method. This method is typically used for creating and configuring the system under test. This means that: We should create the dependencies of the tested object in this method.


2 Answers

Use the @After annotation to indicate the method(s) to be run after every @Test.

The full suite of annotations like this are:

  • @BeforeClass - before all @Tests are run
  • @Before - before each @Test is run
  • @After - after each @Test is run
  • @AfterClass - after all @Tests are run

I just realised I may not have understood the question. If you are asking how to associate a particular teardown method to a particular @Test method, there is no need for annotations: Simply call it at the end of your test method in a finally:

@Test public void someTest() {     try {         // test something     } finally {         someParticularTearDown();     } } 
like image 161
Bohemian Avatar answered Oct 05 '22 11:10

Bohemian


The point of grouping test methods together in the same class is so they can share things, that includes having the same setup and teardown. So, yes, you can define separate teardowns for each test, but you do so by putting the @Test methods in different classes.

Once you start having separate teardown methods the rationale for why you would want to group the tests together in the same class is not apparent. So you could manage this situation by being flexible about how you group your tests in classes.

like image 29
Nathan Hughes Avatar answered Oct 05 '22 13:10

Nathan Hughes