JUnit / Mockito:java.lang.IllegalStateException:“字段”不能为null

时间:2018-10-02 11:38:29

标签: android junit kotlin mockito

我对Mockito和测试还很陌生,但是我无法弄清楚到底是什么问题,这是一个简单的MVP结构

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代码:

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最终将呼叫showResult

谢谢!

1 个答案:

答案 0 :(得分:0)

我不认识科特林,但我认为这条线

activity.presenter = mock()

必须更改为类似

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