0

I have this piece of code

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

and ApiCarouselGroup class is here

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
            }
        };
    }
}

and the problem is items in carouselGroupMock is null

Just for information I want to mention I have this and it works no problem I don't understand what the problem in first case?

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

where 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()
  }
}```
I.S
  • 1,904
  • 2
  • 25
  • 48

1 Answers1

0

I don't think it really answer your question, but i think there is somewhere in your mock trying to invoke source from final class. have you added this dependency?

testImplementation 'org.mockito:mockito-inline:2.13.0' // for final class
Nanda Z
  • 1,604
  • 4
  • 15
  • 37
  • Wasn't `mockito-inline` mainly used for `kotlin`? Check this [`answer`](https://stackoverflow.com/a/40018295/11514534) and/or the [`faq`](https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/Mockito.html#Mocking_Final) instead. – second Aug 28 '19 at 18:54