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?
If you don't want to upgrade to JUnit5 you can use @PostConstruct
it will have the same effect. Example here
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With