Somehow I'm not able to mock via mockito a method and getting null pointer. Not sure why its failing!
import io.github.xxxx.repository.ProductRepository
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.assertj.core.api.Assertions.assertThat
import org.bson.Document
import org.junit.jupiter.api.Test
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import javax.inject.Inject
@MicronautTest
open class OrderServiceTest {
@field:Inject
lateinit var productRepository: ProductRepository
@Test
fun name() {
assertThat(2+3).isEqualTo(5)
// 👇 here I'm getting the error, The method is of type T? so returning null is ok
`when`(productRepository.find("abc")).thenReturn(null);
assertThat(productRepository.find("abc")).isNull()
}
@MockBean(ProductRepository::class)
open fun contextService(): ProductRepository {
return mock(ProductRepository::class.java)
}
}
The exception that I'm getting:
java.lang.NullPointerException
at io.github.imalik8088.repository.ProductRepository.getCollection(ProductRepository.kt:65)
at io.github.imalik8088.repository.ProductRepository.find(ProductRepository.kt:40)
at io.github.imalik8088.service.OrderServiceTest.name(OrderServiceTest.kt:22)
open keyword to Kotlin classesif you working with kotlin i recommend you to use mockk (https://mockk.io/) quite similar to mockito but using the full featureset of kotlins dsl. Regarding your problem, from the stacktrace it seems to me, that the mock does not work. Workin with repos i always recommend to use testcontainer and not mock the repos, cause in reality it could cause a lot of trouble, when the generated sql not works as expected.
But if you want to mock your repo and run some tests on that. Forget about @MicronautTest and just mock the interface like that:
internal class OrderServiceTest {
private val productRepository: ProductRepository = mock(ProductRepository::class.java)
@Test
fun name() {
assertThat(2+3).isEqualTo(5)
`when`(productRepository.find("abc")).thenReturn(null);
assertThat(productRepository.find("abc")).isNull()
}
}
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