首页 > 解决方案 > 断言在 JetPack Compose 测试中是否抛出异常

问题描述

问题

Button(onClick = { throw IllegalArgumentException() }) {
    Text(text = ACTION_THROW_ERROR)
}

我有一个Button. 在其中onClick,我扔了一个IllegalArgumentException. 如何测试是否抛出异常?

我试过的

  1. 我试过@Test注释的expected参数
@Test(expected = IllegalArgumentException::class)
fun throwsError_1() {
    composeRule.onNodeWithText(ACTION_THROW_ERROR).performClick()
}
  1. 我试过正常try-catch
try {
    composeRule.onNodeWithText(ACTION_THROW_ERROR).performClick()
    assert(false)
} catch (e: IllegalArgumentException) {
    assert(true)
}
  1. 我试过了Assert.assertThrows
Assert.assertThrows(IllegalArgumentException::class.java) {
    composeRule.onNodeWithText(ACTION_THROW_ERROR).performClick()
}

这些都不起作用

在此处查看完整的测试文件

问题

标签: androidkotlinjunitandroid-jetpack-composeandroid-instrumentation

解决方案


推荐阅读