Search code examples
androidkotlinjunit4data-class

Android data class unit test


I have a data class below -

data class MyViewState(
    val loading: Boolean = false,
    val data: String? = null,
    val error: String? = null
)

I have a simple JUnit4 test -

@Test
fun testLoading() {
    val myViewState = MyViewState()
    myViewState.copy(loading = true)
    assertEquals(myViewState.loading, true)
}

The test fails. Gives me -

java.lang.AssertionError: 
Expected :false
Actual   :true

Solution

  • You are checking the value in the original object. Use this:

    @Test
    fun testLoading() {
        val myViewState = MyViewState()
        val myViewStateCopy = myViewState.copy(loading = true)
        assertEquals(true, myViewStateCopy.loading)
    }
    

    Also note your expected value should be the first parameter to assertEquals()