junit 如何在android中对onInitializeValidityEvent进行单元测试

vd2z7a6w  于 11个月前  发布在  Android
关注(0)|答案(1)|浏览(219)

在我的android应用程序中,我有3个按钮,当无障碍焦点被清除时,我需要调用一个方法。
为了实现这一目标,我正在做以下工作

fun setUpButton() {
...
   registerFocusChangeEvents(button1)
   registerFocusChangeEvents(button2)
   registerFocusChangeEvents(button3)
...
}

...
private fun registerFocusChangeEvents(button: Button){
    button.accessibilityDelegate = object : AccessibilityDelegate() {
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onInitializeAccessibilityEvent(host: View?, event: AccessibilityEvent?){
        super.onInitializeAccessibilityEvent(host, event)
        if (event?.eventType == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED){
            testMethod()
        }
    }
}

fun testMethod() {
...
}

字符串
在我的JUnit测试类中,

@Test
fun `test focus shift`() {
    val testClass = spy(TestClass(...))

    val testButton1 = testClass.menu.contentView.findViewById<Button>(R.id.btn1)
    val testButton2 = testClass.menu.contentView.findViewById<Button>(R.id.btn2)
    val testButton3 = testClass.menu.contentView.findViewById<Button>(R.id.btn3)

    // I tried the following
    // testButton1.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
    // testButton1.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)

    // testButton2.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
    // testButton2.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)

    // testButton3.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
    // testButton3.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED)

    // testButton1.requestFocus()
    // testButton1.clearFocus()
    // testButton2.requestFocus()
    // testButton2.clearFocus()
    // testButton3.requestFocus()
    // testButton3.clearFocus()

    // testButton1.dispatchTouchEvent(MotionEvent.obtain(0,0, MotionEvent.ACTION_DOWN, 0f, 0f, 0))

    // testButton2.dispatchTouchEvent(MotionEvent.obtain(0,0, MotionEvent.ACTION_DOWN, 0f, 0f, 0))

    // testButton3.dispatchTouchEvent(MotionEvent.obtain(0,0, MotionEvent.ACTION_DOWN, 0f, 0f, 0))

    verify (exactly = 3){ //assertion failed. Method was not called
        testMethod()
    }
}


我已经尝试了上述方法来模拟从按钮的焦点转移。然而,测试失败,因为testMethod()从未被调用。这意味着,它无法触发可访问性焦点更改。我不知道为什么会这样。
其他的想法?

5sxhfpxr

5sxhfpxr1#

结果我只需要

val accessibilityEvent = AccessibilityEvent.obtain(
            AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED
        )

button1.accessibilityDelegate.onInitializeAccessibilityEvent(
            button1, accessibilityEvent
        )
button2.accessibilityDelegate.onInitializeAccessibilityEvent(
            button2, accessibilityEvent
        )
button3.accessibilityDelegate.onInitializeAccessibilityEvent(
            button3, accessibilityEvent
        )
verify(exactly = 3) {
            testClass.testMethod()
        }

字符串

相关问题