简体   繁体   English

Robolectric - Robolectric 中是否有类似于 espresso 的 typeText 的东西?

[英]Robolectric - Is there something in Robolectric similar to espresso's typeText?

In the Robolectric's website ( http://robolectric.org/ ), the product is sold as an alternative without emulator (not instrumented) testing solution enabling full access to Android classes.在 Robolectric 的网站 ( http://robolectric.org/ ) 中,该产品作为替代品出售,无需模拟器(未检测)测试解决方案,可以完全访问 Android 类。

So I would like to know, if like espresso, there is something like the typeText(string) in Robolectric.所以我想知道,如果像浓缩咖啡一样, typeText(string)有类似typeText(string)的东西。

This is because I have associated an OnKeyListener to an EditText which is not being called if I use EditText.setText(string)这是因为我已将OnKeyListenerEditText相关联,如果我使用EditText.setText(string)则不会调用它

You could use dispatchKeyEvent你可以使用dispatchKeyEvent

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

It is possible to create extension fun that typing any input text:可以创建输入任何输入文本的扩展乐趣:

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

If you want to submit Enter for OnKeyListener it would be enought:如果你想为OnKeyListener提交Enter就足够了:

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

But if you listen for onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean it is not enough.但是如果你监听onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean是不够的。 I found that only this approach could work:我发现只有这种方法可以工作:

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

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

So unit test could look like this example:所以单元测试看起来像这个例子:

@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)
                }
            }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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