Search code examples
scalascalatest

Assertion with Array in scala


I am trying to assert the condition but getting error.

I have result of type Either[CaseClass[Array[String]]] with value: Right(CaseClass(Array("value")))

When i do :


result should equal(Right(CaseClass(Array("value"))))


It gives me:


Right(CaseClass([Ljava.lang.String;@6ed4e733) did not equal Right(CaseClass([Ljava.lang.String;@43553bf0))


Solution

  • Array is not a true Scala collections and behaves differently, for example

    List(42) == List(42)    // true
    Array(42) == Array(42)  // false
    

    where we see array is not compared structurally. Now ScalaTest does provide special handling for Array which would indeed compare them structurally

    Array("") should equal (Array(""))            // pass
    

    however it does not work when Array is nested in another container

    case class Foo(a: Array[String])
    Foo(Array("")) should equal (Foo(Array("")))  // fail
    

    True Scala collections, such as List, do not suffer this problem

    case class Bar(a: List[String])
    Bar(List("")) should equal (Bar(List("")))    // pass
    

    There is an open issue Matchers fail to understand Array equality for Arrays wrapped inside a container/collection #491 to address deep equality checks for Array however for now I would suggest switching to List instead of Array. Another options is to provide your own custom equality designed to handle your specific case.