Skip to content

Instantly share code, notes, and snippets.

@dmcg
Created March 25, 2020 12:03
Show Gist options
  • Save dmcg/dff9e38adeda2fc3c3d39b156f4dde63 to your computer and use it in GitHub Desktop.
Save dmcg/dff9e38adeda2fc3c3d39b156f4dde63 to your computer and use it in GitHub Desktop.
Combining Hamkrest and Result4K
import com.natpryce.Failure
import com.natpryce.Result
import com.natpryce.Success
import com.natpryce.hamkrest.MatchResult
import com.natpryce.hamkrest.Matcher
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
fun <T, E> assertSuccessThat(actual: Result<T, E>, valueMatcher: Matcher<T>) {
assertThat(
actual,
isSuccessMatching(valueMatcher))
}
fun <T, E> isSuccessOf(expectedValue: T) = isSuccessMatching<T, E>(equalTo(expectedValue))
fun <T, E> isSuccessMatching(valueMatcher: Matcher<T>) : Matcher<Result<T, E>> = object: Matcher<Result<T, E>> {
override fun invoke(actual: Result<T, E>) = when (actual) {
is Success -> valueMatcher(actual.value)
is Failure -> MatchResult.Mismatch("was Failure[${actual.reason}]")
}
override val description get() = valueMatcher.description
}
fun <T, E> isFailureWithReason(expectedReason: E): Matcher<Result<T, E>> = isFailureMatching(equalTo(expectedReason))
fun <T, E> isFailureMatching(errorMatcher: Matcher<E>) : Matcher<Result<T, E>> = object: Matcher<Result<T, E>> {
override fun invoke(actual: Result<T, E>) = when (actual) {
is Success -> MatchResult.Mismatch("was Success (and should have been Failure)")
is Failure -> errorMatcher(actual.reason)
}
override val description get() = errorMatcher.description
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment