【问题标题】:When using Mockito with Kotlin how do you get around any() must not be null?在 Kotlin 中使用 Mockito 时,如何绕过 any() 不能为空?
【发布时间】:2020-10-12 17:32:41
【问题描述】:

在尝试模拟函数调用 getInventoryList(object, string, int, object, int) 时,我发现我会不断遇到错误 ArgumentMatchers.any() must not be null。

这是我尝试过的一些解决方案。 MockitoHelper

object MockitoHelper {
fun <T> anyObject(): T {
    Mockito.any<T>()
    return uninitialized()
}
@Suppress("UNCHECKED_CAST")
   fun <T> uninitialized(): T =  null as T
}

任何对象弃用函数

ArgumentMatchers.anyObject()

任何(类:T)

ArgumentMatchers.any(Object::class.java)

以上方法均不适用于此特定问题。他们每个人都返回了类似的 must not be null 错误

【问题讨论】:

    标签: java kotlin mockito


    【解决方案1】:

    这是问题的解决方案。告诉 Kotlin,如果返回 null,则使用对象的初始化版本。

    ArgumentMatchers.any(Object::class.java) ?: Object()
    

    这适用于我的解决方案

    【讨论】:

      【解决方案2】:

      在 Kotlin 中使用 mockito 时存在许多问题。

      这个小图书馆负责主要的:https://github.com/nhaarman/mockito-kotlin

      来自wiki

      此外,Mockito 会为调用 any() 之类的方法返回 null 值,这在将它们传递给不可为 null 的参数时可能会导致 IllegalStateException。该库通过尝试创建要返回的实际实例来解决该问题。

      This is how they implement any

      inline fun <reified T : Any> any(): T {
          return Mockito.any(T::class.java) ?: createInstance()
      }
      

      createInstance() is implemented like this:

      inline fun <reified T : Any> createInstance(): T {
          return when (T::class) {
              Boolean::class -> false as T
              Byte::class -> 0.toByte() as T
              Char::class -> 0.toChar() as T
              Short::class -> 0.toShort() as T
              Int::class -> 0 as T
              Long::class -> 0L as T
              Float::class -> 0f as T
              Double::class -> 0.0 as T
              else -> createInstance(T::class)
          }
      }
      
      fun <T : Any> createInstance(kClass: KClass<T>): T {
          return castNull()
      }
      

      【讨论】:

      • 不幸的是,当类没有默认构造函数时,这个库不起作用。至少这是我的经验。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多