2017-09-27 76 views
0

如何使用scala測試比較兩個列表的列表?使用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 

,但它不能正常工作,它說,兩個數組是不同的,當他們實際上是相同的。

我正在使用funsuite進行scala測試。

+0

轉換數組列表IE'VAL實際=名單(行( 「1」, 「2」),行( 「3」 ,「4」))' –

回答

1

請參閱working with containers。您需要通過既可以實現對IE 類元素平等:

  • 標準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 
        } 
    } 
    
0

快速但不是最好的解決方案是將數組轉換爲字符串。

簡而言之::可以通過使用mkstring方法實現它

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