Reputation: 4137
I'm new to java / kotlin. I would like to assert equality on the following class:
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()
// ...
}
What change is required to turn:
class FactoryTest {
@Test
fun testFactorySuccess() {
val args = arrayOf("place", "WEST", "1", "1")
val a = PlaceCommand(*args)
val b = Factory(args) as PlaceCommand
Assert.assertTrue(a.x.equals(b.x))
Assert.assertTrue(a.y.equals(b.y))
Assert.assertTrue(a.direction.equals(b.direction))
}
// ...
}
Into something like:
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))
}
// ...
}
Thanks.
Upvotes: 2
Views: 3980
Reputation: 1313
You can override equals
method on PlaceCommand
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
}
If you use Intellij Idea you can press Alt+Insert
to generate it.
Then just use ==
operator to test for equality
Assert.assertTrue(PlaceCommand(*args) == (Factory(args) as PlaceCommand))
In kotlin ==
is equivalent to a?.equals(b) ?: b === null
. ===
is reference equality
Upvotes: 4