Scalatest -漂亮的错误消息输出?

von4xj4u  于 2023-04-06  发布在  Scala
关注(0)|答案(1)|浏览(134)

当使用scalatest时,任何时候我们必须比较case类的集合,如果其中一个参数与预期的不同,输出是不可读的,我们必须把它放在记事本中并正确格式化,以便找出问题所在。
有没有什么方法可以覆盖scalatest的默认输出,使其更具可读性?
例如:

case class Test(a: String, b: String, c: String)

  "lists" should "match" in {
    val l1 = List(
      Test("a", "b", "c"),
      Test("d", "e", "f"),
      Test("g", "h", "i")
    )

    val l2 = List(
      Test("a", "b", "c"),
      Test("d", "E", "f"),
      Test("g", "h", "i")
    )

    l1 should contain theSameElementsAs l2
  }

输出:

lists
- should match *** FAILED ***
  List(Test("a", "b", "c"), Test("d", "e", "f"), Test("g", "h", "i")) did not contain the same elements as List(Test("a", "b", "c"), Test("d", "E", "f"), Test("g", "h", "i")) (Test.scala:52)

这并不是很糟糕,因为Test case类并不太大,但是如果它是一个大的case类,输出可能会变得非常难看。
我想要的是这样的:

lists
- should match *** FAILED ***
  List(
    Test("a", "b", "c"),
    Test("d", "e", "f"),
    Test("g", "h", "i")
  )
  did not contain the same elements as
  List(
    Test("a", "b", "c"),
    Test("d", "E", "f"),
    Test("g", "h", "i")
  )
  (Test.scala:52)

如果我能让它告诉我有什么不同就更好了。
除了切换测试框架,scalatest还能做到这一点吗?

mpgws1up

mpgws1up1#

考虑使用ScalaTest的diffx-scala

import org.scalatest._
import flatspec._
import com.softwaremill.diffx.scalatest.DiffShouldMatcher._
import com.softwaremill.diffx.generic.AutoDerivation

class ExampleSpec extends AnyFlatSpec with AutoDerivation {

  case class Test(a: String, b: String, c: String)

  "lists" should "match" in {
    val l1 = List(
      Test("a", "b", "c"),
      Test("d", "e", "f"),
      Test("g", "h", "i")
    )

    val l2 = List(
      Test("a", "b", "c"),
      Test("d", "E", "f"),
      Test("g", "h", "i")
    )

    l1 shouldMatchTo(l2)
  }
}

这给出了漂亮的打印匹配错误输出:

ExampleSpec:
lists
- should match *** FAILED ***
  Matching error:
  List(
       0: Test(
            a: a,
            b: b,
            c: c),
       1: Test(
            a: d,
            b: e -> E,
            c: f),
       2: Test(
            a: g,
            b: h,
            c: i)) (MySuite.scala:34)
Execution took 0.19s
1 tests, 1 failed

相关问题:Case class difference with field names on matcher failure

相关问题