简体   繁体   中英

JUnit/Mockito: java.lang.IllegalStateException: “field” must not be null

I'm fairly new to Mockito and testing, but I can't figure out what is wrong with this exactly, this is a simple MVP structure

lateinit var activity: MainActivity

private val aET = mock<EditText>()
private val aValue = "a"
private val bET = mock<EditText>()
private val bValue = "b"
private val resultTextView = mock<TextView>()

private val aMockEditable: Editable = mock()
private val bMockEditable: Editable = mock()


@Before
fun setup() {
    activity = mock()
    activity.presenter = mock()

    whenever(activity.a).thenReturn(aET)
    whenever(activity.b).thenReturn(bET)

    whenever(aET.text).thenReturn(aMockEditable)
    whenever(bET.text).thenReturn(bMockEditable)

    whenever(aMockEditable.toString()).thenReturn(aValue)
    whenever(bMockEditable.toString()).thenReturn(bValue)

    whenever(activity.resultText).thenReturn(resultTextView)
}

@Test
fun onPlus() {
    activity.onPlusClicked()

    verify(activity.presenter).onPlusClicked(aValue, bValue)
}

MainActivity code:

fun onPlusClicked() {
    presenter.onPlusClicked(a.text.toString(), b.text.toString()) // ERROR: java.lang.IllegalStateException: a must not be null
}

override fun showResult(result: String) {
    resultText.text = result
}

presenter will eventually call showResult

Thank you!

I don't know Kotlin but I think the line

activity.presenter = mock()

has to be changed to something like

var presenter = mock()
whenever(activity.presenter).thenReturn(presenter)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM