Search code examples
scaladiffscalatestpretty-printcase-class

Case class difference with field names on matcher failure


munit out-of-the-box shows pretty diffs on assertion failure for case classes which include field names, for example,

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

prints

enter image description here

Are such pretty diffs possible in ScalaTest?


Solution

  • ScalaTest 3.1.0 provides enhanced prettifier out-of-the-box, for example,

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

    prints Analysis section which includes field names but lacks highlighting and formatting

    enter image description here

    To get nicer highlighting and formatting we could try diffx-scalatest, for example,

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

    prints

    enter image description here