Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit @BeforeClass non-static work around for Spring Boot application

JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods. However, this cannot be used with dependency injection.

I want to clean up a database that I @Autowire with Spring Boot, once before I run my JUnit tests. I cannot @Autowire static fields so I need to think of a work around. Any ideas?

like image 601
Kingamere Avatar asked Oct 05 '15 16:10

Kingamere


People also ask

Does BeforeClass have to be static?

JUnit's @BeforeClass annotation must be declared static if you want it to run once before all the @Test methods. However, this cannot be used with dependency injection.

Does BeforeAll need to be static?

@BeforeAll methods must have a void return type, must not be private , and must be static by default. Consequently, @BeforeAll methods are not supported in @Nested test classes or as interface default methods unless the test class is annotated with @TestInstance(Lifecycle.

What is the difference between @BeforeClass and @before in Junit?

The code marked @Before is executed before each test, while @BeforeClass runs once before the entire test fixture. If your test class has ten tests, @Before code will be executed ten times, but @BeforeClass will be executed only once.

What is @BeforeClass in Junit?

org.junitAnnotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those of the current class, unless they are shadowed in the current class.


Video Answer


1 Answers

Just use @Before (instead of @BeforeClass) (or Spring's @BeforeTransaction (depending on how you initialize the database)). This annotation must been attached to an nonstatic public method.

Of course: @Before run before EACH test case method (not like @BeforeClass that runs only once.) But if you want to run it exactly once, then use an static marker field.

private static boolean initialized = false; ... @Before public void initializeDB() {     if (!initialized) {        ... //your db initialization        initialized = true;    } } --- 
like image 79
Ralph Avatar answered Sep 20 '22 08:09

Ralph