Robolectric - Robolectric中有什么类似于espresso的typeText?

时间:2017-10-02 14:09:48

标签: android unit-testing tdd robolectric

在Robolectric的网站(http://robolectric.org/)中,该产品作为替代方案出售,没有模拟器(未经过检测)的测试解决方案,可以完全访问Android类。

所以我想知道,如果像espresso一样,Robolectric中有typeText(string)之类的内容。

这是因为我已将OnKeyListenerEditText相关联,如果我使用EditText.setText(string)

,则该P x y = z 未被调用

1 个答案:

答案 0 :(得分:0)

您可以使用dispatchKeyEvent

editText.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_H))
editText.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_I))
assertEquals("hi", editText.text.toString())

可以通过键入任何输入文本来创建扩展乐趣:

fun EditText.typeText(text: String) {
    val charMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
    val events: Array<KeyEvent> = charMap.getEvents(text.toCharArray())
    for (e in events) {
        this.dispatchKeyEvent(e)
    }
}

如果您想为Enter提交OnKeyListener,那就足够了:

editText.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))

但是,如果您听onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean,那还不够。我发现只有这种方法可行:

fun EditText.performEditorActionDone() {
    this.performEditorAction(EditorInfo.IME_ACTION_DONE)
}

fun EditText.performEditorAction(editorAction: Int) {
    this.onCreateInputConnection(EditorInfo())
        .performEditorAction(editorAction)
}

因此单元测试可能类似于以下示例:

@Test
fun `input name, enter - name is saved`() {
    val p: ExamplePresenter = get(...)

    launchFragmentInContainer<ExampleFragment>().let { scenario ->
        scenario.moveToState(Lifecycle.State.RESUMED)
            .onFragment { fragment ->
                fragment.requireView().findViewById<EditText>(R.id.input_field).let {
                    it.performClick()
                    it.selectAll()
                    it.typeText("hi")
                    assertEquals("hi", it.text.toString())
                    it.performEditorActionDone()
                    assertEquals("hi", p.state.name)
                }
            }
    }
}