5

我想使用 Either 测试获得的结果。假设我有一个没有 Either 的简单示例

@Test
fun `test arithmetic`() {
    val simpleResult = 2 + 2
    Assertions.assertEquals(4, simpleResult)
}

现在我已经包装了结果:

@Test
fun `test arithmetic with either`() {
    val result : Either<Nothing, Int> = (2 + 2).right()
    Assertions.assertTrue(result.isRight())
    result.map { Assertions.assertEquals(4, it) }
}

我想它看起来有点难看,因为如果我们得到了最后的断言,Either.Left而不是Either.Right 如何以函数式正确测试结果,则不会执行最后一个断言?

4

3 回答 3

11

kotlintest提供了一个kotest-assertions-arrow可用于测试箭头类型的模块。

它基本上公开了 Either 和其他数据类型的匹配器。看看这个

@Test
fun `test arithmetic with either`() {
    val result : Either<Nothing, Int> = (2 + 2).right()
    result.shouldBeRight(4)
}
于 2019-02-13T09:50:25.277 回答
5

的实现Either是双方的数据类,因此您可以执行以下操作:

check(result == 4.right())

或者可以使用与任何其他equals用于断言相等性的断言库类似的东西。

于 2019-02-13T21:03:40.850 回答
0

您可以创建扩展功能:

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
}

有了它们,您的测试可能如下所示:

val resultRight : Either<Nothing, Int> = (2 + 2).right()
resultRight
    .assertIsRight()
    .assertEqualsTo(4)

val resultLeft: Either<RuntimeException, Nothing> = RuntimeException("Some exception cause").left()
resultLeft
    .assertIsLeft()
于 2021-11-07T16:56:19.083 回答