Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - How to manage @BeforeClass static method in springBootTest

I want to have a @BeforeClass method in my springBootTest, which should be static and declared in "companion object".

@RunWith(SpringRunner::class)
@SpringBootTest
@ActiveProfiles("test")
open class MyTest {
companion object {

    @Autowired
    lateinit var repo: MyRepository

    @BeforeClass
    @JvmStatic
    fun X() {
        user = User()
        repo.save(user)
    }

}

On the other hand I should use some Autowired components in this method, but as mentioned here is not possible in static context and I got this error:

lateinit property repo has not been initialized

Any suggestion about how should I handle this situation?

like image 474
Mhy Avatar asked Jul 31 '18 11:07

Mhy


2 Answers

If you don't want to upgrade to JUnit5 you can use @PostConstruct it will have the same effect. Example here

like image 164
sergiofbsilva Avatar answered Nov 15 '22 07:11

sergiofbsilva


I suggest you switch to Junit 5. It allows you to use @BeforeAll on regular non-static methods. Also, if you use Junit 5 Spring Extension, you’ll be able to inject dependencies into your @BeforeAll.

How you update the JUnit version will depend on which build tool you use (Maven or Gradle). Also you’ll need to replace @RunWith(SpringRunner::class) with @ExtendWith(SpringExtension::class).

You’ll also need to create the property file src/test/resources/junit-platform.properties with the content: junit.jupiter.testinstance.lifecycle.default = per_class. With this, you will be able to use you to use @BeforeAll on non-static methods.

It might seem a lot, but JUnit 5 is a better fit if you're using Kotlin and Spring Boot.

Reference: Testing with JUnit 5 on Building web applications with Spring Boot and Kotlin

like image 22
Fabricio Lemos Avatar answered Nov 15 '22 07:11

Fabricio Lemos