【问题标题】:Kotlin How to mock generic class in unit test?Kotlin 如何在单元测试中模拟泛型类?
【发布时间】:2021-01-31 02:42:51
【问题描述】:

我正在尝试在 kotlin 中模拟 MongoCollection 类

class MyTest {

  val mockCollection: MongoCollection<Document> = mock(MongoCollection<Document>::class.java)

}

它给出了一个错误类字面量的左侧只允许使用类

在研究了一下我发现了这个 only classes are allowed on the left hand side of a class literal 我尝试为 MongoCollection 创建一个类型,然后将其传递给模拟,但它给出了一个错误,因为模拟是 Type

我还尝试将模拟转换为 Document,如下所示

val mockCollection: MongoCollection<Document> = mock(MongoCollection::class.java) as MongoCollection<Document>

但在代码实现内部访问 MongoCollection 期间会产生 NullpointerException 异常。

我都试过了

而且他们都有同样的错误?

我厌倦了在 java 中编写相同的测试并在其中进行泛型转换。

MongoCollection<Document> mockCollection = (MongoCollection<Document>) mock(MongoCollection.class);

有人有在 Kotlin 中模拟泛型类的经验吗?

【问题讨论】:

    标签: java unit-testing kotlin mocking mockito


    【解决方案1】:

    我为你写了下面的例子:

    interface Mosi<T> {
        fun mos(): T
    }
    

    那么下面所有三个用于测试和测试的代码sn-ps都通过了:

    class ExampleUnitTest {
    
        val mosi = Mockito.mock(Mosi::class.java)
        @Test
        fun test() {
            `when`(mosi.mos()).thenReturn("Mosi")
            assertEquals(mosi.mos(), "Mosi")
        }
    }
    
    class ExampleUnitTest {
    
        val mosi = Mockito.mock(Mosi::class.java) as Mosi<String>
        @Test
        fun test() {
            `when`(mosi.mos()).thenReturn("Mosi")
            assertEquals(mosi.mos(), "Mosi")
        }
    }
    
    class ExampleUnitTest {
    
        val mosi = mock<Mosi<String>> {
            on { mos() }
                .thenReturn("Mosi")
        }
        @Test
        fun test() {
            assertEquals(mosi.mos(), "Mosi")
        }
    }
    

    如果您收到 NPE 问题出在其他地方,也许提供更多代码会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2017-06-14
      相关资源
      最近更新 更多