ScalaTest: customized value output for predefined type

时间:2015-06-30 13:34:53

标签: scala scalatest

Say, I have trivial test like this:

class Test extends FunSuite with Matchers {

  test("test") {
    val array = Array(
      Array(1, 1, 1),
      Array(2, 1, 3),
      Array(1, 4, 1)
    )

    array should equal (null)
  }

}

... that fails as:

Array(Array(1, 1, 1), Array(2, 1, 3), Array(1, 4, 1)) did not equal null

My array represents game field, and I'd like it to be printed in test output similar to:

1 1 1
2 1 3
1 4 1

... instead of:

Array(Array(1, 1, 1), Array(2, 1, 3), Array(1, 4, 1))

Is there a way to do this in ScalaTest?

2 个答案:

答案 0 :(得分:2)

使用的一个选项是WithClue。像这样的东西

val a = Array( Array(1,2,3), Array(4,5,6),Array(7,8,9))
def p (x:Array[Array[Int]]) = x.foreach( x=> {x.foreach(print);println;} )
withClue(p(a) ) {a should equal (null)}

我觉得你会想要覆盖匹配器。正如我所看到的那样,接下来会将Array Array与Array Array进行比较,您可能会在比较失败的情况下寻找非常具体的比较。

答案 1 :(得分:0)

这很有趣。
您可以考虑使用其他类和伴随对象将数组包装在should之前。类和伴侣必须是这样的,它们不会使您的null测试无效,但提供更漂亮的印刷品。例如:

class ArrayPrettyPrinter(array : Array[Int]) {
   override def toString() : String = {
      // your pretty print implementation here
   }
}

object ArrayPrettyPrinter {
   def apply(array : Array[Int]) : ArrayPrettyPrinter = {
      if (array == null) return null
      return new ArrayPrettyPrinter(array)
   }
}

你的测试应该成为:

class Test extends FunSuite with Matchers {

  test("test") {
    val array = Array(
      Array(1, 1, 1),
      Array(2, 1, 3),
      Array(1, 4, 1)
    )

    ArrayPrettyPrinter(array) should equal (null)
  }    
}