1

im using a sealed class to report back success or error to client code:

sealed class Result<out T : Any> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

But im stuck getting even the simplest unit test to compile using it:

    val error = Result.Error(IOException("message"))
    assertThat(error, instanceOf(Result.Error::class.java))

I get the message : Type Inference failed. Not enough information to infer parameter T in fun instanceOf(type : Class<*>) : Matcher!

Looks like im missing something important in Kotlin.

Thanks for helping me out!

Kitesurfer
  • 3,438
  • 2
  • 29
  • 47

3 Answers3

8

there is no problem with your code for me.

import org.hamcrest.CoreMatchers.instanceOf
import org.junit.Test

import org.junit.Assert.*
import java.io.IOException

class ExampleUnitTest {
    @Test
    fun test1() {
        val error = Result.Error(IOException("message"))
        assertTrue(error is Result.Error)
    }

    @Test
    fun test2() {
        val error = Result.Error(IOException("message"))
        assertThat(error , instanceOf(Result.Error::class.java))
    }

    sealed class Result<out T : Any> {
        data class Success<out T : Any>(val data: T) : Result<T>()
        data class Error(val exception: Exception) : Result<Nothing>()
    }
}

Also, I'll suggest you to use the keyword is to check if your class is an instance of something in kotlin (like in test1)

  • Took my a while to come back here. using assertThat with instanceOf or 'is' makes no difference and may be a matter of choice. – Kitesurfer May 03 '19 at 09:58
  • Using `instanceOf` has a better error message. It indicates which type was received. Using `is` just returns a bool and you have to figure out which type was sent. – hopia Oct 08 '22 at 00:04
1

To avoid ::class I prefer this.

assertThat(result is Result.Error).isTrue()

HariKrishnan
  • 456
  • 3
  • 14
0

Looks like i was looking in the false API. As im mostly using assertj. Below code is clean and fluent to read

assertThat(result).isInstanceOf(Result.Error::class.java)
Kitesurfer
  • 3,438
  • 2
  • 29
  • 47