我正在尝试测试Activity
,它会立即在onCreate
中启动Bluetooth-Enable-Intent:
class EnableBluetoothActivity : Activity() {
val requestEnableBluetooth = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivityForResult(
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),
requestEnableBluetooth)
}
}
这是我使用意式浓缩咖啡的仪器测试:
@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.
我该怎么做才能使测试正常进行?谢谢!
答案 0 :(得分:0)
好像您是在模拟器或打开了蓝牙的设备上运行测试。您可以检查蓝牙的状态/状态(不确定最好的方法是什么)或使用以下try-catch hack:
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
}