你可以使用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)
}
}
如果您想为OnKeyListener 提交Enter 就足够了:
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)
}
}
}
}