【问题标题】:Mock Kotlin class in Java unit testJava单元测试中的模拟Kotlin类
【发布时间】:2016-10-06 17:52:07
【问题描述】:

我用 Mockito 进行了这个 Java 测试:

public class PersistentNodeDeserializerTests {

    @Test
    public void userInfoPersistentNodeDeserializer() {
        PersistentNode node = mock(PersistentNode.class);
        when(node.stringChild("username")).thenReturn("cliff12");
        //more stuff
    }

}

PersistentNode 是一个 Kotlin 类:

open class PersistentNode(private val path: PersistentNodePath, val content: Any) {

    val stringPath: String
        get() = path.get()

    val key: String
        get() {
            val parts = stringPath.split("/");
            return parts[parts.size - 1];
        }

    val mapContent: Map<String, Any>
        get() {
            return content as HashMap<String, Any>
        }

    fun stringChild(child: String): String {
        return mapContent.get(child) as String
    }

}

我收到此错误:

kotlin.TypeCastException: null 不能转换为非 null 类型 java.util.HashMap

如何正确模拟属性stringChild?

【问题讨论】:

    标签: unit-testing kotlin


    【解决方案1】:

    这个库可以解决你的问题https://github.com/nhaarman/mockito-kotlin

    编辑:抱歉,没有意识到您正在使用 Java 测试。如果可以,请尝试在 kotlin 中编写测试

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多