kotlin-result
kotlin-result copied to clipboard
Assertion helpers for tests
Would you be open to adding helper functions for using Results in tests?
For example:
inline fun <reified V, reified E> Result<V, E>.assertOk(): V {
assertIs<Ok<V>>(this)
return value
}
Usage:
fun doSomething(): Result<String, Exception> {
// ...
}
@Test
fun test() {
val success: String = doSomething().assertOk()
}
I suppose this could live in a kotlin-result-test package or similar, which has a dependecy on the multiplatform kotlin.test package and also exports the functions as described in your post. What I would like to avoid is forcing people who use the core library to consume the kotlin.test library in their runtime code, instead they would do something like dependencies { testImplementation('...:kotlin-result-test:..') }
I use slightly modified versions of the proposed functions:
inline fun <V, E> Result<V, E>.assertOk(assertion: (value: V) -> Unit) {
try {
assertion.invoke(this.expect { "Expected the result to be an Ok, found an Err instead" })
} catch (e: UnwrapException) {
fail(e.message)
}
}
inline fun <V, E> Result<V, E>.assertErr(assertion: (err: E) -> Unit) {
try {
assertion.invoke(this.expectError { "Expected the result to be an Err, found an Ok instead" })
} catch (e: UnwrapException) {
fail(e.message)
}
}
Usage:
fun doSomething(): Result<String, Exception> {
// ...
}
@Test
fun test() {
doSomething().assertOk { assertEquals("expected", it) }
}
I find that in majority of the cases the assertion ends up being assertEquals so there might be merit in introducing a shortcut for that case:
inline fun <V, E> Result<V, E>.assertOkEquals(expected: V) {
try {
assertEquals(expected, this.expect { "Expected the result to be an Ok, found an Err instead" })
} catch (e: UnwrapException) {
fail(e.message)
}
}
// Usage
@Test
fun test() {
doSomething().assertOkEquals("expected")
}