8

I am running JUnit tests that test a Spring Boot application. I have a @Before method and an @After one. Then I have a bunch of @Test methods which are the actual tests.

However, my @Before and @After methods execute before and after each test, respectively, instead of executing once before all the tests, and once after all the tests.

Could it be that I'm also using this annotation?

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kingamere
  • 9,496
  • 23
  • 71
  • 110
  • I'm afraid that if you want to execute some code for the whole test suite (whatever it is) you have to develop some code to do this. For that purpose I've created a singleton (a class with an static field) and make sure that kept track of every invocation, so that only the first time invoked did something. – Raul Luna Oct 04 '15 at 16:34

2 Answers2

29

This is the normal behaviour of @Before and @After. Quoting the documentation of @Before, for example:

Annotating a public void method with @Before causes that method to be run before the Test method.

If you want to run a method only once before and after all the tests, you can use @BeforeClass and @AfterClass. Quoting the documentation of @BeforeClass for example:

Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
4

That is exactly what @Before and @After are supposed to do. If you want to run some setup code before an entire test class, you should use @BeforeClass. In the same fashion, if you want to tear down after an entire test class has been executed, you should use @AfterClass. Note that the methods these two annotations are applied to should be public static and take no arguments.

Mureinik
  • 297,002
  • 52
  • 306
  • 350