Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Either from Arrow in functional style

I would like to test the obtained result using Either. Let's assume I have a simple example without Either

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

And now i have wrapped result:

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

I suppose it looks a little bit ugly, because the last Assertions will not be executed if we got Either.Left instead of Either.Right How can I test the result properly in functional style?

like image 664
Bukharov Sergey Avatar asked Feb 13 '19 09:02

Bukharov Sergey


Video Answer


2 Answers

kotlintest provides a kotest-assertions-arrow module which can be used to test Arrow types.

It basically expose matchers for Either and other data type. Take a look at this.

@Test
fun `test arithmetic with either`() {
    val result : Either<Nothing, Int> = (2 + 2).right()
    result.shouldBeRight(4)
}
like image 189
noiaverbale Avatar answered Oct 13 '22 08:10

noiaverbale


The implementations of Either are data classes on both sides so you can do something like:

check(result == 4.right())

Or can use something similar with any other assertion library that uses equals to assert equality.

like image 5
pablisco Avatar answered Oct 13 '22 08:10

pablisco