Kotlin类实例assertEqual
我是新来的java / kotlin。 我想在下面的课堂上坚持平等:
class PlaceCommand(vararg args: String) : ICommand { var direction: Direction = Direction.valueOf(args[1].toUpperCase()) var x: Int = args[2].toInt() var y: Int = args[3].toInt() // ... }
需要改变什么:
class FactoryTest { @Test fun testFactorySuccess() { val args = arrayOf("place", "WEST", "1", "1") val a = PlaceCommand(*args) val b = Factory(args) as PlaceCommand Assert.assertTrue(axequals(bx)) Assert.assertTrue(ayequals(by)) Assert.assertTrue(a.direction.equals(b.direction)) } // ... }
像这样的东西:
class FactoryTest { @Test fun testFactorySuccess() { val args = arrayOf("place", "WEST", "1", "1") Assert.assertEqual(PlaceCommand(*args), Factory(args) as PlaceCommand) # or Assert.assertTrue(PlaceCommand(*args).equal(Factory(args) as PlaceCommand)) } // ... }
谢谢。
您可以在PlaceCommand上覆盖equals
方法
override fun equals(other: Any?): Boolean{ if (this === other) return true if (other?.javaClass != javaClass) return false other as PlaceCommand if (x != other.x) return false if (y != other.y) return false return true }
如果您使用Intellij Idea,则可以按Alt+Insert
来生成它。
然后使用==
运算符来测试是否相等
Assert.assertTrue(PlaceCommand(*args) == (Factory(args) as PlaceCommand))
在kotlin ==
相当于a?.equals(b) ?: b === null
。 ===
是参考平等