【问题标题】:Play framework specs2 weird matcher syntax播放 framework specs2 奇怪的匹配器语法
【发布时间】:2016-01-27 17:28:29
【问题描述】:

在 Play framework specs2 测试中,我有这些行...

    new WithApplication {
      val homeResponse = route(FakeRequest(GET, "/")).get
      val resultType = contentType(homeResponse)
      resultType.must( beSome.which( _ == "text/html") )
    }

^ 这可行,但是当我将“ beSome.which( _ == "text/html") ”拉到一个单独的变量中时...

    new WithApplication {
      val homeResponse = route(FakeRequest(GET, "/")).get
      val resultType = contentType(homeResponse)
      val textTypeMatcher = beSome.which( _ == "text/html")
      resultType.must( textTypeMatcher )
    }

^ 类型不匹配。

预期:Matcher[Option[String]],实际:OptionLikeCheckedMatcher[Option, Nothing, Nothing] ^

这里发生了什么?

【问题讨论】:

  • 可能是根据resultType推断出_的类型。怎么样:val textTypeMatcher = beSome[String].which( _ == "text/html")
  • 你不需要.which(_ == "text/html") 部分,beSome("text/html") 工作正常。

标签: scala specs2


【解决方案1】:

在第一种情况下,它根据resultType.must( 推断类型,因为resultType 是String。但是当你拆分它时,没有什么可以推断的,所以你会得到:

val textTypeMatcher = beSome.which( _ == "text/html")
=> OptionLikeCheckedMatcher[Option, Nothing, Nothing]

但是如果你添加类型:beSome[String],你会再次得到正确的类型。

val textTypeMatcher = beSome[String].which( _ == "text/html")
=> OptionLikeCheckedMatcher[Option, String, String]

编辑:

您也可以这样做:

val textTypeMatcher: OptionLikeCheckedMatcher[Option, String, String] = beSome.which( _ == "text/html")

所以基本上,如果你给类型推断器一些可以使用的东西,它会推断_ 必须是一个字符串。否则,Scala 无法知道_ 应该是一个字符串。

【讨论】:

  • 哦,我明白了。因为用户可以指定他们想要比较任何泛型类型——int、float,你命名它,到字符串。所以你也可以这样做:“val textTypeMatcher = beSome.which(docType: String => docType == "text/html")
猜你喜欢
  • 1970-01-01
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多