为什么模拟数据返回null?

时间:2019-08-28 14:16:53

标签: android mocking mockito android-testing

我有这段代码

 carouselGroupMock = mock(ApiCarouselGroup::class.java).apply {
      `when`(items).thenReturn(listOf("tvChannels", "featured"))
    }

和ApiCarouselGroup类 在这里

class ApiCarouselGroup @Throws(IOException::class)
constructor(jsonReader: JsonReader) : IApiPageLayoutComponent {
  var items: List<String>? = null

  init {
    jsonReader.beginObject()
    while (jsonReader.hasNext()) {
      when (jsonReader.nextName()) {
        "items" -> this.items = JsonReaderUtil.readArray(jsonReader, String::class.java)
        else -> jsonReader.skipValue()
      }
    }
    jsonReader.endObject()
  }

  override fun toPresenterModel(): PageComponent.CarouselGroup {
    return PageComponent.CarouselGroup(items ?: emptyList())
  }
}

interface IApiPageLayoutComponent {
    fun toPresenterModel() : PageComponent

    companion object {
        val FACTORY : JsonReaderUtil.IObjectFactory<IApiPageLayoutComponent> = JsonReaderUtil.IObjectFactory<IApiPageLayoutComponent> {
            jsonReader ->
            val jsonObject = JsonReaderUtil.JSON_OBJECT_FACTORY.newInstance(jsonReader)
            when(jsonObject.getString("type")) {
                "heroBanners" -> ApiHeroBannerGroup(JsonReader(StringReader(jsonObject.toString())))
                "carousels" -> ApiCarouselGroup(JsonReader(StringReader(jsonObject.toString())))
                else -> null
            }
        };
    }
}

问题是carouselGroupMock中的项目为空

仅供参考,我想提及我的意思,它没问题 我不明白第一种情况是什么问题?

mainMenuMock = mock(ApiMainMenu::class.java).apply {)
      `when`(actions).thenReturn(listOf(actionMock))
    }

其中ApiMainMenu

class ApiMainMenu @Throws(IOException::class)
constructor(jsonReader: JsonReader) {
  var type: String? = null
  var titles: List<ApiTitle>? = null
  var actions: List<ApiAction>? = null

  init {
    jsonReader.beginObject()
    while (jsonReader.hasNext()) {
      when (jsonReader.nextName()) {
        "action" -> this.actions = JsonReaderUtil.readArray(jsonReader, ApiAction::class.java)
        else -> jsonReader.skipValue()
      }
    }
    jsonReader.endObject()
  }
}```

1 个答案:

答案 0 :(得分:0)

我认为它不能真正回答您的问题,但是我认为您的模拟中有某个地方试图从最终类中调用源代码。 您添加了此依赖性吗?

testImplementation 'org.mockito:mockito-inline:2.13.0' // for final class