scala - 使用 scalatest 自定义相等
问题描述
我想做一个非常简单的例子来演示如何在对数字使用相等匹配器时自定义相等:
(29.0001) should equal (29.0) (+-0.0002)
我知道你可以直接对这种事情使用范围检查,但这就是我想要展示的。接受其他一些建议,以显示用于自定义相等性的简单单行。
非常感谢
解决方案
从文档中提取:
组织自定义匹配器的一种好方法是将它们放在一个或多个特征中,然后您可以将它们混合到需要它们的套件中。这是一个例子:
import org.scalatest._
import matchers._
trait CustomMatchers {
class FileEndsWithExtensionMatcher(expectedExtension: String) extends Matcher[java.io.File] {
def apply(left: java.io.File) = {
val name = left.getName
MatchResult(
name.endsWith(expectedExtension),
s"""File $name did not end with extension "$expectedExtension"""",
s"""File $name ended with extension "$expectedExtension""""
)
}
}
def endWithExtension(expectedExtension: String) = new FileEndsWithExtensionMatcher(expectedExtension)
}
// Make them easy to import with:
// import CustomMatchers._
object CustomMatchers extends CustomMatchers
然后你可以写
import org.scalatest._
import Matchers._
import java.io.File
import CustomMatchers._
new File("essay.text") should endWithExtension ("txt")