预计 Android Espresso 测试中会出现异常 - 失败

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

我正在使用 Kotlin 在 Espresso 中为我的 Android 应用程序编写测试。 我希望像单元测试中那样期待异常,并在发现此类异常时通过测试。

我进行了一项测试,检查 Intent extras 格式。 在实现中,我在意图中获得不正确的值后引发了异常。 我想通过测试是抛出这个异常。运行测试结果时显示“测试失败”和

java.lang.IllegalArgumentException
,这与我试图捕获的相同。

我一开始尝试使用这个注释:

@Test(expected = IllegalArgumentException::class)

然后我尝试使用

org.jetbrains.kotlin:kotlin-test
依赖项和以下断言:

assertFailsWith<java.lang.IllegalArgumentException> {
    val activityIntent = Intent()
    activityIntent.putExtra("extra_connection_number", intentExtraConnectionNumber)
    activityRule.launchActivity(activityIntent)
}

同样重要的是,异常是在

onCreateView
中抛出的,如下所示:

@Throws(java.lang.IllegalArgumentException::class)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
    val layout = inflater.inflate(R.layout.configuration_fragment, container, false)
    var connectionNumber: Int? =
        activity!!.intent.getIntExtra(resources.getString(R.string.extra_connection_number), -1)
    if (connectionNumber == -1) {
        throw IllegalArgumentException()
    }
(...)

意图是使用给定的额外内容创建的,但它在我希望它失败的地方失败了。但抛出的异常不会被 Espresso 捕获。 为什么?我错过了什么?

我知道它可能与 Espresso 不兼容,但我找不到合适的文档来帮助我解决问题。

android unit-testing kotlin exception android-espresso
2个回答
1
投票

使用正常的 try catch 解决了我的问题,我知道异常是嵌套的。但我们仍然可以通过原因来检查:

var error: Throwable? = null
try {
    onView(something).perform(click())
} catch (e: Throwable) {
    error = e;
}
assert(error!!.cause is MySpecificException)
assert(error!!.cause!!.message == "My specific error message")

我尝试了另一种方法,但我最终得到了不稳定的测试结果。


0
投票

我有一个非常类似的错误。

我使用

requireNotNull
方法检查片段中的参数。我想检查当这个特定的额外值不存在时是否抛出 IllegalArgumentException 。我正在使用
ActivityScenario
来测试这一点,因为参数是由活动意图提供的。

片段按预期抛出异常,但测试没有捕获异常,并且在抛出异常的那一刻就完成了。我尝试了不同的方法,但总是失败:

  • @Test(expected = IllegalArgumentException::class)
  • @Test(expected = Exception::class)
  • assertFailsWith<IllegalArgumentException>
  • assertFailsWith<Exception>
  • 使用
    try catch
    黑色

有人知道如何测试这个场景吗?

© www.soinside.com 2019 - 2024. All rights reserved.