kotlin Kaspresso.如何无例外地显示检查元素

cu6pst1q  于 2023-06-24  发布在  Kotlin
关注(0)|答案(1)|浏览(163)

我想检查authauthorization屏幕显示kaspresso但isDisplyed()不返回布尔值,我有错误。
如何无例外地显示check元素
现在我的解决方案:

  1. fun isNeedAuth(): Boolean {
  2. return try {
  3. authButton.isEnabled()
  4. true
  5. } catch (e: NullPointerException) {
  6. false
  7. }
  8. }
8ljdwjyq

8ljdwjyq1#

我个人使用:

  1. fun safeAssertion(assert: () -> Unit) =
  2. try {
  3. assert()
  4. true
  5. } catch (_: Throwable) {
  6. false
  7. }

在测试中,它看起来像:

  1. if (safeAssertion { authButton.isEnabled() }) { doSomething() }

此外,您还可以为KViews创建扩展:

  1. fun <K : BaseAssertions> K.safeAssert(assert: K.() -> Unit) = safeAssertion { assert() }

并使用它像:

  1. if (authButton.safeAssert { isDisplayed() }) { doSomething() }

等待所需状态的更高级解决方案:

  1. fun waitUntilConditionMet(
  2. description: String = "",
  3. maxWaitTime: Duration = 10.seconds,
  4. retryInterval: Duration = 250.milliseconds,
  5. onFail: () -> Unit = { throw MyCustomWaitingFailedException(maxWaitTime, description) },
  6. conditionToMeet: () -> Boolean
  7. ) {
  8. try {
  9. runBlocking {
  10. withTimeout(maxWaitTime) {
  11. while (!conditionToMeet()) {
  12. delay(retryInterval)
  13. }
  14. }
  15. }
  16. } catch (e: Throwable) {
  17. Log.e("My Custom Waiter", e.message ?: "Failed to meet condition in ${maxWaitTime.inWholeSeconds} seconds")
  18. onFail()
  19. }
  20. }

用法示例(如果条件在10秒内未满足,则将引发异常):

  1. waitUntilConditionMet("Some screen appeared") {
  2. safeAssertion {
  3. someButton.isDisplayed()
  4. anotherView.isEnabled()
  5. }
  6. }

或者不抛出异常:

  1. waitUntilConditionMet(
  2. description = "Some screen appeared",
  3. onFail = { doSomethingIfConditionIsNotMet() }
  4. ) {
  5. safeAssertion {
  6. someButton.isDisplayed()
  7. anotherView.isEnabled()
  8. }
  9. }
展开查看全部

相关问题