【问题标题】:Case class difference with field names on matcher failure匹配器失败时与字段名称的案例类差异
【发布时间】:2020-05-18 10:05:40
【问题描述】:

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 中是否可以实现如此漂亮的差异?

【问题讨论】:

    标签: scala diff scalatest pretty-print case-class


    【解决方案1】:

    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)
      }
    }
    

    打印

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2021-09-14
      相关资源
      最近更新 更多