Kotlin类实例assertEqual

时间:2016-05-18 05:16:31

标签: java kotlin

我是java / kotlin的新手。我想在下面的类中声明相等:

<?php
    $recd = $_POST['ID'];
    echo $recd;

需要进行哪些更改:

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(a.x.equals(b.x))
        Assert.assertTrue(a.y.equals(b.y))
        Assert.assertTrue(a.direction.equals(b.direction))
    }

    // ...
}

感谢。

1 个答案:

答案 0 :(得分:4)

您可以在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===是引用相等