Me gustaría probar el resultado obtenido usando cualquiera. Supongamos que tengo un ejemplo simple sin Ambos
@Test fun `test arithmetic`() { val simpleResult = 2 + 2 Assertions.assertEquals(4, simpleResult) }Y ahora he envuelto el resultado:
@Test fun `test arithmetic with either`() { val result : Either<Nothing, Int> = (2 + 2).right() Assertions.assertTrue(result.isRight()) result.map { Assertions.assertEquals(4, it) } } Supongo que se ve un poco feo, porque las últimas Either.Left no se ejecutarán si tenemos Cualquiera.Izquierda en lugar de Either.Right ¿Cómo puedo probar el resultado correctamente en estilo funcional?
kotlintest proporciona un kotest-assertions-arrow que se puede usar para probar los tipos de flecha.
Básicamente, expone los emparejadores para cualquiera y otros tipos de datos. Echa un vistazo a esto .
@Test fun `test arithmetic with either`() { val result : Either<Nothing, Int> = (2 + 2).right() result.shouldBeRight(4) }Las implementaciones de Either son clases de datos en ambos lados, por lo que puede hacer algo como:
check(result == 4.right()) O puede usar algo similar con cualquier otra biblioteca de aserciones que use equals para afirmar la igualdad.
Puede crear funciones de extensión:
fun <L, R> Either<L, R>.assertIsLeft(): L { return when (this) { is Either.Left -> value is Either.Right -> throw AssertionError("Expected Either.Left, but found Either.Right with value $value") } } fun <L, R> Either<L, R>.assertIsRight(): R { return when (this) { is Either.Right -> value is Either.Left -> throw AssertionError("Expected Either.Right, but found Either.Left with value $value") } } fun <T: Any> T.assertEqualsTo(expected: T): Boolean { return this == expected }Con ellos, tus pruebas podrían verse así:
val resultRight : Either<Nothing, Int> = (2 + 2).right() resultRight .assertIsRight() .assertEqualsTo(4) val resultLeft: Either<RuntimeException, Nothing> = RuntimeException("Some exception cause").left() resultLeft .assertIsLeft()