使用scala测试比较嵌套列表

时间:2017-09-27 09:16:30

标签: scala scalatest

如何使用scala测试比较两个列表列表?

val actual = Array(Row("1", "2"), Row("3", "4"))
val fail_expected = Array(Row("1", "2"), Row("3", "2"))
val pass_expected = Array(Row("3", "4"), Row("1", "2"))

我试过

actual should contain theSameElementsAs pass_expected

但它没有用,它说这两个数组是不同的,当它们实际上是相同的时候。

我正在使用带有scala测试的funsuite。

2 个答案:

答案 0 :(得分:1)

working with containers。您需要通过以下任一方式为元素Row类实现相等性:

  • 标准的Scala方式,如:

    class Row(val elems: String*) {
    
        def canEqual(other: Any): Boolean = other.isInstanceOf[Row]
    
        override def equals(other: Any): Boolean = other match {
          case that: Row =>
            (that canEqual this) &&
              elems == that.elems
          case _ => false
        }
    
        override def hashCode(): Int = {
          val state = Seq(elems)
          state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
        }
    }
    object Row {
        def apply(elems: String*) = new Row(elems: _*)
    }
    

    或简单地将其作为案例类:

    case class Row(elems: String*)
    
  • 或提供隐式Equality[Row]实施:

    import org.scalactic.Equality
    implicit object RowEquals extends Equality[Row] {
        override def areEqual(a: Row, b: Any): Boolean = b match {
          case r: Row => a.elems == r.elems
          case _ => false
        }
    }
    

答案 1 :(得分:0)

快速但不是最好的解决方案是将数组转换为字符串。您可以使用mkstring方法实现它:

简而言之:

 actual.mkstring(",") == pass_expected.mkstring(",")