7

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?

Fabricio Lemos
  • 2,905
  • 2
  • 31
  • 31
Mhy
  • 187
  • 3
  • 10
  • Autowire cannot autowire static fields at all. Setup your repo before each test, not before the class is your only real option. – Darren Forsythe Jul 31 '18 at 11:21

2 Answers2

3

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

sergiofbsilva
  • 1,606
  • 15
  • 20
1

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

Fabricio Lemos
  • 2,905
  • 2
  • 31
  • 31
  • Thank you. I tried your solution. Autowired components don't get initialized when I replace `@RunWith(SpringRunner::class)` with `@ExtendWith(SpringExtension::class)`. Any Idea? Another problem is `@BeforeAll` method doesn't get invoked! I am using Maven. I tried [this answer](https://stackoverflow.com/questions/49441049/junit-5-does-not-execute-method-annotated-with-beforeeach) but still no luck. – Mhy Aug 04 '18 at 06:02
  • Please post the new code, it will make it better to analyse the problem. You can see a working example of bean autowiring here: https://github.com/fabriciolemos/kotlin-spring-boot-lab/blob/master/src/test/kotlin/com/example/blog/ArticleResourceTest.kt – Fabricio Lemos Aug 07 '18 at 14:54
  • the problem was spring-boot-starter-test dependency in my pom.xml, which is using junit4 (unless you exclude it). I excluded junit from spring-boot-starter-test in pom and everything works fine now. – Mhy Aug 12 '18 at 13:24