我有一个活动SomeActivity
。为了正常工作,它需要一个 id。这个 id 在 Intent 中传递。
SomeActivity
在其onCreate
-Method 中检索 Intent 中的 id。如果它为空,它会抛出一个错误(这会使 Activity 崩溃)。
我想使用仪器测试来测试这种行为。到目前为止我的代码:
SomeActivity.kt
class SomeActivity: AppCompatActivity() {
private var id: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_someActivity)
id = intent.extras?.getString("EXTRA_ID")
if (id == null) {
throw Error("id is null")
}
}
}
仪表化测试:SomeActivityInstrumentedTest.kt
@RunWith(AndroidJUnit4::class)
class SomeActivityInstrumentedTest{
@get: Rule
public var rule: ActivityScenarioRule<*> = ActivityScenarioRule(SomeActivity::class.java)
@Test
fun launchActivity() {
try {
val scenario = rule.scenario as ActivityScenario<SomeActivity>
scenario.moveToState(Lifecycle.State.CREATED)
scenario.moveToState(Lifecycle.State.STARTED)
scenario.moveToState(Lifecycle.State.RESUMED)
Assert.fail("should have failed earlier because id is not set")
} catch (e: Error) {
assertEquals(e.message, "id is null")
}
}
}
我从来没有发现错误,测试只是崩溃了。有什么方法可以捕捉到这个错误吗?