0

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
Ma2340
  • 647
  • 2
  • 17
  • 34

3 Answers3

3

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()

Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
1

Your assert is checking the value of myViewState which has not changed.

Store the result of copy in a new object and test against that.

@Test
fun testLoading() {
    val myViewState = MyViewState()
    val myNewViewState = myViewState.copy(loading = true)
    assertEquals(myNewViewState.loading, true)
}
Ivan Wooll
  • 4,145
  • 3
  • 23
  • 34
1

The problem is that you're testing the old object, not the copied one.

Do this instead:

@Test
fun testLoading() {
    val myViewState = MyViewState()
    val myViewStateCopy = myViewState.copy(loading = true)
    assertEquals(true, myViewStateCopy.loading)
}
Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49