Search code examples
androidkotlinjunit

assertEquals does not properly evaluate test junit parameterized


I am creating a test to test If my class mapper works correctly. The mapper is correct but somehow assertEquals does not properly recognize that my actual and expected are equals it says its pointing to different object so its not equals

@RunWith(Parameterized::class)
class PaginationToPresentationMapperTest(
    private val given: PaginationDomainModel,
    private val expected: PaginationPresentationModel
) {
    companion object {
        @JvmStatic
        @Parameters(name = "Given {0} then {1}")
        fun data(): Collection<Array<*>> = listOf(
            testCase(
                nextCursor = null,
                prevCursor = null
            ),
            testCase(
                nextCursor = "next_id",
                prevCursor = null
            ),
            testCase(
                nextCursor = null,
                prevCursor = "prev_id"
            )
        )

        private fun testCase(
            nextCursor: String?,
            prevCursor: String?
        ) = arrayOf(
            PaginationDomainModel(
                nextCursor = nextCursor,
                prevCursor = prevCursor
            ),
            PaginationPresentationModel(
                nextCursor = nextCursor,
                prevCursor = prevCursor
            )
        )
    }

    private lateinit var classUnderTest: PaginationToPresentationMapper

    @Before
    fun setUp() {
        classUnderTest = PaginationToPresentationMapper()
    }

    @Test
    fun `When toPresentation`() {
        // given

        // when
        val actual = classUnderTest.toPresentation(given)

        // then
        assertEquals(expected, actual)
    }
}

Fail:

expected:<link.limecode.newsfeed.presentation.model.pagination.PaginationPresentationModel@7bd7d6d6> but was:<link.limecode.newsfeed.presentation.model.pagination.PaginationPresentationModel@50029372>
Expected :link.limecode.newsfeed.presentation.model.pagination.PaginationPresentationModel@7bd7d6d6
Actual   :link.limecode.newsfeed.presentation.model.pagination.PaginationPresentationModel@50029372

Solution

  • You need to override the equals method of your PaginationPresentationModel. By default, the equals method only compares instance equality, so two different objects with the same field values will not be equal.

    If you use a data class, Kotlin will generate a value-based equals for you automatically.