2013-04-28 106 views
2

我已更新我的問題,刪除舊文本,使其更容易閱讀。斯卡拉spec2 object.productID必須_ ==「123」失敗

scalaVersion := "2.10.1" 
"org.specs2"   %% "specs2"  % "1.13" % "test" 

我SPEC2測試:

package com.mycompany.dataminer.parser 

import org.specs2.mutable.Specification 

case class Product(productID:String) 

class SimpleTest extends Specification { 

    "product" should { 

    "have id = 123" in { 
     var product1 = Product("123") 
     product1 must not beNull 
     product1.productID must_== "123" 

     var product2 = Product("123") 
     product2 must not beNull 
     product2.productID must_== "123" 

     var product3 = Product("123") 
     product3 must not beNull 
     product3.productID must_== "123" 
    } 
    } 

} 

結果:

scala: type mismatch; 
found : String 
required: org.specs2.matcher.Matcher[com.mycompany.dataminer.parser.Product] 
     product1.productID must_== "123" 
      ^

有一次,我寫了這個代碼,這是工作,直到我添加此行:

product1 must not beNull 
product2 must not beNull 
product3 must not beNull 

回答

4

這是問題Scala的表達解析(半列推理)以及specs2模型匹配器的方式。

具有第一個匹配器product1 must not beNull的行被解釋爲product1.must(not) beNull。這意味着beNull處於沒有參數的方法調用的位置,但如果它有參數,它們必須是Matcher[Product]。這是因爲整個表達式的類型爲MatchResult[Product],而MatchResult特徵的方法爲apply

結果是Scala推斷第一行表達式的參數位於第二行product1.productID,並且類型String這是意外的。

有這種情況3級的解決方法:

  • 換行符

    product1 must not beNull 
    
    product1.productID must_== "123" 
    
  • 半柱

    product1 must not beNull; 
    product1.productID must_== "123" 
    
  • 一個parenthetised not

    product1 must not(beNull) 
    
    product1.productID must_== "123" 
    

這將在未來的版本specs2通過使MatchResult[T].apply方法私人爲了編譯錯誤轉化爲method apply in trait MatchResult cannot be accessed in org.specs2.matcher.MatchResult[Product]並在此方法中Scaladoc添加潛在問題的描述來緩解。

+0

我已將此問題發佈到spec2問題跟蹤器(爲了不忘記:)) – ses 2013-04-28 22:46:46

1

我的猜測:

  1. 導入名稱衝突,或
  2. 什麼不對勁的規格

也許下面的驗收測試的例子可能提供了一個線索:

 
import org.specs2.Specification 
import xyz.{Product => TestProduct} // <- Alias the "Product" package

trait MyTestHelper { val pId = "123" lazy val product = new TestProduct.Product(pId, ...) // <-- Class to test }

class MyTest extends Specification with MyTestHelper { def is = ("Product should be " + pId) ! product.ProductID must be_==("123")^ end }

+0

我提供了新的說明。我想現在很容易重現。 – ses 2013-04-28 22:20:06