[英]In Kotlin, how can one unit test that a data class, sealed class, or class field are not changed?
[英]Kotlin sealed class and type inference
我使用密封類向客戶端代碼報告成功或錯誤:
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>()
}
但是我堅持使用它來編譯最簡單的單元測試:
val error = Result.Error(IOException("message"))
assertThat(error, instanceOf(Result.Error::class.java))
我收到消息:類型推斷失敗。 沒有足夠的信息來推斷 fun instanceOf(type : Class<*>) 中的參數 T:匹配器!
看起來我在 Kotlin 中遺漏了一些重要的東西。
謝謝你的協助!
你的代碼對我來說沒有問題。
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>()
}
}
另外,我建議您使用關鍵字is
檢查您的類是否是 kotlin 中某物的實例(如 test1)
看起來我正在尋找虛假的 API。 因為我主要使用assertj。 下面的代碼是干凈和流暢的閱讀
assertThat(result).isInstanceOf(Result.Error::class.java)
為了避免 ::class 我更喜歡這個。
assertThat(result is Result.Error).isTrue()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.