Android:测试蓝牙启用意图(Espresso-Intents仪器测试)

问题描述 投票:0回答:1

我正在尝试测试我的Activity,它在onCreate中立即启动蓝牙启用意图:

class EnableBluetoothActivity : Activity() {

    val requestEnableBluetooth = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivityForResult(
            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
            requestEnableBluetooth)
    }
}

这是我使用espresso-intents的仪器测试:

@RunWith(AndroidJUnit4::class)
@MediumTest
class EnableBluetoothActivityUITests {

    private var bluetoothAdapter: BluetoothAdapter? = null

    @get:Rule
    val activityRule = IntentsTestRule<EnableBluetoothActivity>(
        EnableBluetoothActivity::class.java)

    // Init Bluetooth adapter in setUp()

    @Test
    fun bluetoothIsDisabled_startsEnableDialogIntent() {

        intended(IntentMatchers.hasAction(
            BluetoothAdapter.ACTION_REQUEST_ENABLE))

    }
}

但它给了我以下错误:

junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 0 intents.

IntentMatcher: has action: is "android.bluetooth.adapter.action.REQUEST_ENABLE"

Matched intents:[]

Recorded intents:[]
at junit.framework.Assert.fail(Assert.java:50)
at android.support.test.espresso.intent.VerificationModes$Times.verify(VerificationModes.java:80)
at android.support.test.espresso.intent.Intents.internalIntended(Intents.java:316)
at android.support.test.espresso.intent.Intents$3.run(Intents.java:203)
at android.support.test.espresso.intent.Intents$PropogatingRunnable.run(Intents.java:223)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:1980)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Tests ran to completion.

我该怎么做才能让我的测试工作?谢谢!

android kotlin android-espresso android-bluetooth
1个回答
0
投票

您似乎正在模拟器或打开蓝牙的设备上运行测试。您可以检查蓝牙的状态/状态(不确定最佳方法)或使用以下try-catch黑客:

    try {
        intended(IntentMatchers.hasAction(BluetoothAdapter.ACTION_REQUEST_ENABLE))
    } catch (e: AssertionFailedError) {
        // The intent didn't appear, so the Bluetooth is turned on or doesn't exist at all
    }
© www.soinside.com 2019 - 2024. All rights reserved.