在 ScalaTest 匹配中忽略大小写 class 字段

Ignore case class field in ScalaTest matching

假设我的案例 class 有几个字段成员:

case class User(name: String, ..., createdAt: LocalDateTime)

如何在不考虑 createdAt 字段的情况下检查相等性?

有没有更好的方法:

val expected = User("username", stubDate)
actual shouldBe expected.copy(createdAt = actual.createdAt)

像这样考虑matchPattern

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

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

  "User" should "be Worf where we ignore the age" in {
    val actual = User("Worf", 30)
    actual should matchPattern { case User("Worf", _) => }
  }
}

或定义custom equality

import org.scalactic.Equality
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class CaseClassPatternMatchSpec extends AnyFlatSpec with Matchers {
  case class User(name: String, age: Int)
  object User {
    implicit val aEq: Equality[User] = (a: User, b: Any) => b match {
      case User(name, _) => a.name == name
      case _ => false
    }
  }

  "User" should "be Worf where we ignore the age " in {
    val actual = User("Worf", 30)
    val expected = User("Worf", -11)
    actual should === (expected)
  }
}

仅注意某些匹配器

result should equal (3) // can customize equality
result should === (3)   // can customize equality and enforce type constraints
result shouldEqual 3    // can customize equality, no parentheses required