
jvmMain.io.kotest.matchers.future.matchers.kt Maven / Gradle / Ivy
package io.kotest.matchers.future
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.kotest.matchers.shouldNotBe
import java.util.concurrent.CompletableFuture
fun CompletableFuture.shouldBeCompletedExceptionally() = this shouldBe completedExceptionally()
fun CompletableFuture.shouldNotBeCompletedExceptionally() = this shouldNotBe completedExceptionally()
fun completedExceptionally() = object : Matcher> {
override fun test(value: CompletableFuture): MatcherResult =
MatcherResult(
value.isCompletedExceptionally,
{ "Future should be completed exceptionally" },
{
"Future should not be completed exceptionally"
})
}
fun CompletableFuture.shouldBeCompleted() = this shouldBe completed()
fun CompletableFuture.shouldNotBeCompleted() = this shouldNotBe completed()
fun completed() = object : Matcher> {
override fun test(value: CompletableFuture): MatcherResult =
MatcherResult(
value.isDone,
{ "Future should be completed" },
{
"Future should not be completed"
})
}
fun CompletableFuture.shouldBeCancelled() = this shouldBe cancelled()
fun CompletableFuture.shouldNotBeCancelled() = this shouldNotBe cancelled()
fun cancelled() = object : Matcher> {
override fun test(value: CompletableFuture): MatcherResult =
MatcherResult(
value.isCancelled,
{ "Future should be completed" },
{
"Future should not be completed"
})
}
infix fun CompletableFuture<*>.shouldCompleteExceptionallyWith(throwable: Throwable) =
this should completeExceptionallyWith(throwable)
infix fun CompletableFuture<*>.shouldNotCompleteExceptionallyWith(throwable: Throwable) =
this shouldNot completeExceptionallyWith(throwable)
internal fun completeExceptionallyWith(throwable: Throwable) = object : Matcher> {
override fun test(value: CompletableFuture<*>): MatcherResult {
val exception = value.runCatching { get() }.exceptionOrNull()
return MatcherResult(
exception != null && exception.cause == throwable,
{ errorMessageForTestFailure(exception?.cause, throwable) },
{ "Expected future not to fail with ${exception?.cause}, but it did fail with it." }
)
}
}
internal fun errorMessageForTestFailure(actualException: Throwable?, expectedException: Throwable): String {
if (actualException == null) {
return "Expected future to fail with $expectedException, but it did not failed with any exception"
}
return "Expected future to fail with $expectedException, but it failed with $actualException"
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy