2017-04-20 26 views
0

我已經創建並使用Lists和適當類型的一些外部Scalacheck生成器,使用Gen.oneOf(List[T])。我認爲偶爾有用的是返回一個空值的佔位符。目前該列表已填充。我應該怎麼做呢?我是否試圖將一個空的類型追加到列表的末尾?如果是這樣,我該怎麼做?如果沒有,我還能如何讓我的發生器添加一個空值。這看起來很簡單,但我現在無法搞清楚。屬性檢查應該在Scalatest中失敗

import org.scalatest.FlatSpec 
import org.scalacheck.Gen 
import org.scalacheck.Prop.exists 
import org.scalatest.prop.PropertyChecks 

class EventFieldGeneratorTest extends FlatSpec with PropertyChecks { 
    behavior of "Gen.option" 
    it should "occasionally return None" in { 
    val colors = Gen.oneOf("Blue", "Red", "Green", "Yellow") 
    val opt = Gen.option(colors) 
    val list = Gen.listOfN(20, opt) 
    val p1 = exists(list)(_ == None) 
    p1.check 
    } 
} 

有人可以解釋爲什麼我的測試放棄嗎?

Testing started at 10:31 AM ... ! Gave up after only 0 passed tests. 501 tests were discarded. 

Process finished with exit code 0 

我該如何將該標記標記爲ScalaTest的失敗結果?對我來說使用Flatspec是不是一個好主意?

也許我應該使用比check以外的東西......

這是我習慣了排序的文檔。在Scalatest頁:

http://www.scalatest.org/user_guide/writing_scalacheck_style_properties

回答

1

我不認爲有什麼缺陷,試圖使用列表和可選值。只有幾個問題會導致麻煩。

這很讓人困惑,但如果您使用Scalatest框架,則需要使用Scalatest基礎結構來使用Scalacheck。所以你需要使用Scalatest匹配器,並編寫Scalatest風格的屬性(使用它的forAll),但是你仍然會直接使用Scalacheck的生成器。

由於某種原因,列表與Option類型之間的類型推斷給您帶來麻煩。如果使用shouldBe匹配,

x shouldBe(None) 

,你會從Scalatest得到一個相關運行時錯誤:

[info] - should occasionally return None *** FAILED *** 
[info] TestFailedException was thrown during property evaluation. 
[info]  Message: List() was not equal to None 
[info]  Location: (GenTest.scala:13) 
[info]  Occurred when passed generated values (
[info]  arg0 = List() // 5 shrinks 
[info] ) 
[info] Run completed in 1 second, 621 milliseconds. 
[info] Total number of tests run: 1 
[info] Suites: completed 1, aborted 0 
[info] Tests: succeeded 0, failed 1, canceled 0, ignored 0, pending 0 

你不應該有Option型匹配的列表。你需要與Scalatest 「容器」 匹配來匹配should contain

import org.scalatest.FlatSpec 
import org.scalatest.Matchers 
import org.scalacheck.Gen 
import org.scalatest.prop.PropertyChecks 

class EventFieldGeneratorTest extends FlatSpec with Matchers with PropertyChecks { 
    behavior of "Gen.option" 
    it should "occasionally return None" in { 
    val colors = Gen.oneOf("Blue","Red","Green","Yellow") 
    val opt = Gen.option(colors) 
    val list = Gen.listOfN(20,opt) 
    forAll(list) { (xs: List[Option[String]]) => 
     xs should contain (None) 
    } 
    } 
} 

這給你一個成功的地產檢查:

[info] EventFieldGeneratorTest: 
[info] Gen.option 
[info] - should occasionally return None 
[info] ScalaTest 
[info] Run completed in 1 second, 9 milliseconds. 
[info] Total number of tests run: 1 
[info] Suites: completed 1, aborted 0 
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0 
[info] All tests passed. 
[info] Passed: Total 1, Failed 0, Errors 0, Passed 1 

更多關於Scalatest匹配器

http://www.scalatest.org/user_guide/using_matchers