kotlin-result icon indicating copy to clipboard operation
kotlin-result copied to clipboard

Assertion helpers for tests

Open ashughes opened this issue 3 years ago • 2 comments

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()
}

ashughes avatar Mar 30 '22 22:03 ashughes

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:..') }

michaelbull avatar Mar 31 '22 16:03 michaelbull

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")
}

curioustechizen avatar Oct 19 '22 08:10 curioustechizen