[英]Expecting an exception in Android Espresso test - fails
I am writing tests in Espresso for my Android application using Kotlin.我正在使用 Kotlin 在 Espresso 中为我的 Android 应用程序编写测试。 I want to expect an exception as in the unit test and pass the test if such an exception is found.
我希望在单元测试中出现异常,并在发现此类异常时通过测试。
I had a test that was checking for the Intent extras format.我有一个测试是检查 Intent extras 格式。 In the implementation I have thrown an exception after getting an incorrect value in the intent.
在实现中,我在意图中获得了不正确的值后抛出了一个异常。 I want to pass the test is this exception is thrown.
我想通过测试是抛出这个异常。 Running the test results with a "Test failed" and
java.lang.IllegalArgumentException
which is the same as I am trying to catch.使用“测试失败”和
java.lang.IllegalArgumentException
运行测试结果,这与我试图捕获的相同。
I tried with this annotation at first:我一开始尝试使用这个注释:
@Test(expected = IllegalArgumentException::class)
Then I tried with a org.jetbrains.kotlin:kotlin-test
dependency and the following assertion:然后我尝试使用
org.jetbrains.kotlin:kotlin-test
依赖项和以下断言:
assertFailsWith<java.lang.IllegalArgumentException> {
val activityIntent = Intent()
activityIntent.putExtra("extra_connection_number", intentExtraConnectionNumber)
activityRule.launchActivity(activityIntent)
}
What may be also important is that the exception is thrown in the onCreateView
starting as so:同样重要的是在
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()
}
(...)
The intent is created with the given extra, and it is failing in a place I wanted it to fail.这个意图是用给定的额外创建的,它在我希望它失败的地方失败了。 But the thrown exception is not caught by the Espresso.
但是抛出的异常不会被 Espresso 捕获。 Why?
为什么? What am I missing?
我错过了什么?
I am aware it may be incompatible with Espresso, but I cannot find a right documentation helping me with the problem.我知道它可能与 Espresso 不兼容,但我找不到帮助我解决问题的正确文档。
Use normal try catch solved my problem, i know the exception is nested.使用普通的 try catch 解决了我的问题,我知道异常是嵌套的。 But we can still check it by cause:
但是我们仍然可以通过原因来检查它:
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")
I have tried another approach , but i ended up with flaky tests result.我尝试了另一种方法,但最终得到了不稳定的测试结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.