JUnit @Before and @After executing before and after every test
Solution 1
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 theTest
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.
Solution 2
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.
Kingamere
Updated on July 27, 2022Comments
-
Kingamere almost 2 years
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)