【问题标题】:Robolectric - Is there something in Robolectric similar to espresso's typeText?Robolectric - Robolectric 中是否有类似于 espresso 的 typeText 的东西?
【发布时间】:2018-03-13 14:58:12
【问题描述】:

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

所以我想知道,如果喜欢 espresso,Robolectric 中有类似 typeText(string) 的东西。

这是因为我已将 OnKeyListener 与 EditText 相关联,如果我使用 EditText.setText(string) 则不会调用它

【问题讨论】:

    标签: android unit-testing tdd robolectric


    【解决方案1】:

    你可以使用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)
                    }
                }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-04
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多