【问题标题】:Customize equality with scalatest使用 scalatest 自定义相等
【发布时间】:2020-07-12 22:56:03
【问题描述】:

我想做一个非常简单的例子来演示如何在对数字使用相等匹配器时自定义相等:

(29.0001) should equal (29.0) (+-0.0002)

我知道您可以直接对此类事情使用范围检查,但这正是我想要展示的。接受其他一些建议,以显示用于自定义相等性的简单单行。

非常感谢

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    the documentation 中提取:

    组织自定义匹配器的一种好方法是将它们放在一个或多个特征中,然后您可以将它们混合到需要它们的套件中。这是一个例子:

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

    【讨论】:

      【解决方案2】:

      Scalacheck 的匹配器不是那么好。 你可以在你的测试套件中创建你自己的,几乎是单行的。

      implicit class ShouldDeltaEqaulsOps(val d: Double) extends AnyVal {
        def shouldIntervalEqual(d1: Double)(eps: range): Unit := {
          // range check
          d1 + eps > d && d > d1 - eps shouldBe true. 
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 2017-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多