You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ScalaTest匹配器测试属性是否满足指定条件而非相等性?

问题翻译

可以用have来检查属性是否等于某个值,有没有办法不检查相等性,而是验证属性是否满足某个匹配器?下面的代码能编译但无法正常工作,因为它是在把属性和匹配器值做相等性测试:

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

class MainTest extends AnyFlatSpec with Matchers {
  case class Book(title: String, author: List[String], pubYear: Int)
  "Something" should "work" in {
    val book = Book("Programming in Scala", List("Odersky", "Spoon", "Venners"), 2008)
    book should have (
      Symbol("title") ("Programming in Scala"),
      Symbol("pubYear") (be >= 2006 and be <= 2010)
    )
  }
}

解决方案

你需要用matching方法包裹匹配器,让have验证属性是否满足匹配器规则,而非做相等性对比。修改后的代码如下:

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

class MainTest extends AnyFlatSpec with Matchers {
  case class Book(title: String, author: List[String], pubYear: Int)
  "Something" should "work" in {
    val book = Book("Programming in Scala", List("Odersky", "Spoon", "Venners"), 2008)
    book should have (
      'title ("Programming in Scala"),
      'pubYear matching (be >= 2006 and be <= 2010)
    )
  }
}

如果觉得更直观,也可以拆分属性验证逻辑:

book should have ('title ("Programming in Scala"))
book.pubYear should (be >= 2006 and be <= 2010)

要是需要更复杂的自定义属性校验,还可以创建PropertyMatcher:

val pubYearInRange = new PropertyMatcher[Book] {
  def apply(book: Book) = MatchResult(
    book.pubYear >= 2006 && book.pubYear <= 2010,
    s"出版年份${book.pubYear}不在2006-2010区间内",
    s"出版年份${book.pubYear}符合2006-2010区间要求"
  )
}

// 使用示例
book should have (pubYearInRange)

内容的提问来源于stack exchange,提问作者Suma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:55:24