How can I test sealed classes in Kotlin? for examp...
# android
r
How can I test sealed classes in Kotlin? for example I have
Copy code
sealed class LoginResult {
    object Success : LoginResult()
    object WrongCredentials : LoginResult()
    data class InvalidData(val error: ErrorType) : LoginResult()
}

sealed class ErrorType {
    object EmptyEmail : ErrorType()
    object InvalidEmailFormat : ErrorType()
    object EmptyPassword : ErrorType()
}
how can I assert that I got the result of
InvalidData
with the error of
EmptyEmail
?
l
I would check if
Copy code
error is EmptyEmail
r
I can do
assertTrue(result is LoginResult.InvalidData)
How can I check that the error is empty email?
I can do
val x = result as LoginResult.InvalidData
assertTrue(x.error is ErrorType.EmptyEmail)
but I am sure there is a better way
r
You can use
assertIs
to type check the
result
. This will smart cast
result
so you can directly access
error
🔥 3
Copy code
assertIs<LoginResult.InvalidDate>(result)
assertIs<ErrorType.EmptyEmail>(result.error)
https://kotlinlang.org/api/latest/kotlin.test/kotlin.test/assert-is.html
r
Unresolved reference: assertIs
this should be part of Kotlin right?
r
It's part of the kotlin.test library. You should add the following dependency to your tests:
Copy code
testImplementation(kotlin("test"))
r
Thanks a lot man, you have been a great help
👍🏻 1
👍 1
556 Views