Case class 与匹配器失败时的字段名称不同

Case class difference with field names on matcher failure

munit 开箱即用显示了案例 类 的断言失败的相当大的差异,其中包括字段名称,例如,

class CaseClassPrettyDiffSpec extends munit.FunSuite {
  case class User(name: String, age: Int)

  test("User should be Picard") {
    val expected = User("Picard", 67)
    val actual = User("Worf", 30)
    assertEquals(actual, expected)
  }
}

打印

在 ScalaTest 中可能存在如此大的差异吗?

ScalaTest 3.1.0 提供 enhanced prettifier 开箱即用,例如,

import com.softwaremill.diffx.scalatest.DiffMatcher
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class CaseClassPrettyDiffSpec extends AnyFlatSpec with Matchers {
  case class User(name: String, age: Int)

  "User" should "be Picard" in {
    val expected = User("Picard", 67)
    val actual = User("Worf", 30)
    actual should be (expected)
  }
}

打印 Analysis 包含字段名称但缺少突出显示和格式设置的部分

为了更好地突出显示和格式化,我们可以尝试 diffx-scalatest,例如,

class CaseClassPrettyDiffSpec extends AnyFlatSpec with Matchers with DiffMatcher {
  case class User(name: String, age: Int)

  "User" should "be Picard" in {
    val expected = User("Picard", 67)
    val actual = User("Worf", 30)
    actual should matchTo(expected)
  }
}

打印