Issue
I have a simple test case (because I didn't find another way to do it) to load my database with some random data:
package com.springbootapirest.app
import com.springbootapirest.app.models.Dog
import com.springbootapirest.app.repositories.DogRepository
import org.jeasy.random.EasyRandom
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import java.util.stream.Collectors
internal class InitializationTest() {
@Autowired
private lateinit var dogRepository: DogRepository
@Test
fun initializeDatabase() {
val generator = EasyRandom()
val dogs: List<Dog> = generator.objects(Dog::class.java, 3)
.collect(Collectors.toList())
println(dogs);
dogs.forEach { dog ->
this.dogRepository.save(dog);
}
}
}
But when I try to execute with ./gradlew test --tests InitializationTest
The error fragment is
kotlin.UninitializedPropertyAccessException: lateinit property dogRepository has not been initialized
And I don't find how I must initialize the MongoRepository to work exactly the same way as if the Spring Boot API service was running.
Any other simple approach or help will be welcome, thanks.
Solution
At the end was to easy as add @SpringBootTest
in the header of the class:
@SpringBootTest
internal class InitializationTest() {
@Autowired
private lateinit var dogRepository: DogRepository
@Test
fun initializeDatabase() {
val generator = EasyRandom()
val dogs: List<Dog> = generator.objects(Dog::class.java, 3)
.collect(Collectors.toList())
println(dogs);
dogs.forEach { dog ->
this.dogRepository.save(dog);
}
}
}
Answered By - Juan Antonio
Answer Checked By - Candace Johnson (JavaFixing Volunteer)