【问题标题】:Scala specs2 matcher for a File's extension用于文件扩展名的 Scala specs2 匹配器
【发布时间】:2012-07-18 21:15:05
【问题描述】:

我正在尝试创建一个 specs2 匹配器,它断言 File 扩展的有效性(通过重用现有的 endWith 匹配器)。但是我得到一个类型错误。我怎么能绕过它?

import java.io.File
import org.specs2.mutable.Specification
import org.specs2.matcher.{ Expectable, Matcher }

class SampleSpec extends Specification {
  def hasExtension(extension: => String) = new Matcher[File] {
    def apply[S <: File](actual: Expectable[S]) = {
      actual.value.getPath must endWith(extension)
    }
  }
}

这是编译器错误:

<console>:13: error: type mismatch;
 found   : org.specs2.matcher.MatchResult[java.lang.String]
 required: org.specs2.matcher.MatchResult[S]
             actual.value.getPath must endWith(extension)

【问题讨论】:

    标签: scala matcher specs2


    【解决方案1】:

    您确实可以使用^^ 运算符(从解析器组合运算符中获得灵感)并简单地编写:

    def hasExtension(extension: =>String) = endWith(extension) ^^ ((_:File).getPath)
    

    here 提供了创建自定义匹配器的各种方法供参考。

    【讨论】:

    • 谢谢!我喜欢它的简洁。是否没有运算符可以执行相同的操作但参数已交换?我认为它的作用会更清楚一些。
    • 这是个好建议。您现在可以使用最新的 1.12-SNAPSHOT 进行此操作: def haveExtension(extension: =>String) = ((_:File).getPath) ^^ endWith(extension)
    【解决方案2】:

    好的,我已经通过使用 ^^ 运算符来使其工作,该运算符适应匹配器类型。在我看来,它就像一个仿函数的映射函数。

    def hasExtension(extension: => String) = new Matcher[File] {
      def apply[S <: File](actual: Expectable[S]) = {
        actual must endWith(extension) ^^ ((file: S) => file.getPath)
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 2011-07-31
      • 1970-01-01
      相关资源
      最近更新 更多