JUnit参数化测试中assertEquals未正确判定对象相等问题求助
解决assertEquals判定对象不相等的问题
我正在创建测试类验证PaginationToPresentationMapper的正确性,确认映射器逻辑无误,但使用assertEquals时,系统提示实际对象与期望值指向不同引用,未判定二者相等。
测试代码
@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) } }
失败日志
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
问题原因与解决方案
原因:Java/Kotlin中默认的
equals()方法是比较对象的内存引用,而非属性值。PaginationPresentationModel类未重写equals()和hashCode()方法,导致即使两个对象的nextCursor和prevCursor属性完全一致,也会因是不同实例被判定为不相等。解决方案:
- 推荐方案:将
PaginationPresentationModel改为Kotlin的data class,data class会自动生成基于属性的equals()、hashCode()和toString()方法:data class PaginationPresentationModel( val nextCursor: String?, val prevCursor: String? ) - 手动实现:若无法改为data class,手动重写
equals()和hashCode()方法,确保比较逻辑基于对象属性值:class PaginationPresentationModel( val nextCursor: String?, val prevCursor: String? ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PaginationPresentationModel if (nextCursor != other.nextCursor) return false if (prevCursor != other.prevCursor) return false return true } override fun hashCode(): Int { var result = nextCursor?.hashCode() ?: 0 result = 31 * result + (prevCursor?.hashCode() ?: 0) return result } }
- 推荐方案:将
内容的提问来源于stack exchange,提问作者Renz Salanga
相关产品推荐
相关产品推荐

