Meesam Haider
Meesam Haider

Reputation: 41

Handle multiple exceptions in Kotlin Kotest eventually

As per kotest docs: https://github.com/kotest/kotest/blob/master/doc/nondeterministic.md

You can tell eventually to ignore specific exceptions and any others will immediately fail the test.

I want to pass multiple exceptions to eventually that I know would be thrown by my block so that I can explicitly skip them.

Right now I only see a way to pass one, how do I pass more than one exception to eventually to skip it in case the block throws those exceptions?

Upvotes: 4

Views: 927

Answers (2)

Karsten Gabriel
Karsten Gabriel

Reputation: 3682

The module kotest-framework-concurrency contains an eventually that allows to specify multiple suppressed exceptions.

There is the possibility to specify a set of exception types:

eventually({
  duration = 8000
  suppressExceptions = setOf(UserNotFoundException::class)
}) {
  userRepository.getById(1).name shouldNotBe "bob"
}

And, there is the possibility to specify a predicate for exceptions:

eventually({
  duration = 8000
  suppressExceptionIf = { it is UserNotFoundException && it.username == "bob" }
}) {
  userRepository.getById(1).name shouldNotBe "bob"
}

Alternatively, you can specify when the test is considered to be in the state that a failure can actually be regarded as failure:

var string = "x"
eventually({
  duration = 5.seconds()
  predicate = { it.result == "xxx" }
}) {
  string += "x"
  string
}

Upvotes: 1

Maxim Kochetkov
Maxim Kochetkov

Reputation: 76

You may use superclass for all your exceptions like

eventually(200.milliseconds, exceptionClass = RuntimeException::class) {
   throw IllegalStateException()
}

or wrap exceptions

eventually(200.milliseconds, exceptionClass = IllegalStateException::class) {
    runCatching { throw UnknownError() }
        .onFailure { throw IllegalStateException(it) }
}

In 4.4.3 there are no features with collection of Exception

Upvotes: 0

Related Questions