Reputation: 3561
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!
Upvotes: 1
Views: 5059
Reputation: 356
To avoid ::class I prefer this.
assertThat(result is Result.Error).isTrue()
Upvotes: 1
Reputation: 3561
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)
Upvotes: 0
Reputation: 789
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)
Upvotes: 8