gpt4 book ai didi

kotlin - Micronaut 和 kotin 中的 Mockito 不起作用

转载 作者:行者123 更新时间:2023-12-04 03:36:17 25 4
gpt4 key购买 nike

不知何故,我无法通过 mockito 方法来模拟并获取空指针。不知道为什么它失败了!

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)
}
}
我得到的异常(exception):
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)
添加/解决方案/发现:
  • 我发现 Kotest使用 Micronaut 框架和 kotlin AFAIU 的方法如果我正在使用的带有 junit 扩展的 testcontainers 正在使用该
  • mockk 用于 mock ,因为本地和惯用语。 Mockito 在 final类 AFAIK 方面存在问题,例如Spring-Boot 使用内部添加的 lib 解决了 open Kotlin 类的关键字
  • 还发现了 docs不完整或不是很精确,从 kotest 使用的导入或方法已被弃用,并且在它提到的源代码中使用 kotest..
  • 对于我正在做的方面来说,这对于生产关键产品来说不是很重要,它会有所帮助 - 我的 2 美分......也可能缺乏框架和语言方面的知识(两者都是菜鸟状态:))
  • 最佳答案

    如果您使用 kotlin,我建议您使用与 mockito 非常相似的 mockk(https://mockk.io/),但使用 kotlins dsl 的完整功能集。关于您的问题,从堆栈跟踪来看,在我看来,模拟不起作用。使用 repos 我总是建议使用 testcontainer 而不是模拟 repos,因为实际上它可能会导致很多麻烦,当生成的 sql 没有按预期工作时。
    但是,如果您想模拟您的存储库并对其进行一些测试。
    忘记@MicronautTest 并像这样模拟界面:

    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()
    }
    }

    关于kotlin - Micronaut 和 kotin 中的 Mockito 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66825103/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com