2014-09-03 57 views
1

我想用scalacheck測試一個java類。 例如,我有... \ SRC \主\的java內的類隊列\用ScalaCheck測試java類

public class Queue<Item> { 

private Node first; 
private Node last; 
private int N; 

private class Node { 
    Item item; 
    Node next; 
} 

public boolean isEmpty() { return first == null; } 
public int size() { return N;} 

public void enqueue(Item item) { 
    Node oldLast = last; 
    last = new Node(); 
    last.item = item; 
    last.next = null; 
    if(isEmpty()) 
     first = last; 
    else 
     oldLast = last; 
    N++; 
} 

public Item dequeue() { 
    Item item = first.item; 
    first = first.next; 
    if(isEmpty()) 
     last = null; 
    N--; 
    return item; 
} 

}

然後,我必須... \ SRC \測試內的階測試類QueueTest.scala \ scala \

import org.scalacheck.Gen.{choose, oneOf} 
import org.scalacheck.Prop.forAll 
import org.scalacheck.Gen.choose 
import org.scalacheck._ 
import org.scalacheck.Prop._ 

class QueueTest extends Properties("Queue") { 

    Queue<Int> q; 

    property("enque") = Prop.forAll { (n: Int) => 
     (q.enque(n) == n) 
    } 
} 

我只是需要一個關於如何擴展一個java通用Queue類的開端? 我想要做的就是測試入隊和出隊方法。

我看過Rick Nillson的github中的StringUtils.scala示例,但它仍然不清楚。

任何建議,將不勝感激

+0

這是一個完整的代碼,我試圖測試。 http://introcs.cs.princeton.edu/java/43stack/Queue.java.html – 3ek 2014-09-23 16:25:43

回答

1

唯一可能的測試enque是調用,並確保不會拋出異常。

如果這是我的任務,我會爲所有List[Int]定義一個屬性,並測試入隊和出隊任意列表的項目,以便隊列以與列表相同的順序返回完全相同的項目。


按照要求,這裏有一些例子:

import org.scalacheck.Properties 
import org.scalacheck.Prop.forAll 

object QueueSpec extends Properties("Queue") { 

    property("enqueue never throws an exception") = forAll {(xs: List[Int]) => 
    val q = new Queue[Int] 
    xs.foreach(q.enqueue) 
    true 
    } 

    property("dequeue always presents elements in FIFO order") = forAll {(xs: List[Int]) => 
    val q = new Queue[Int] 
    xs.foreach(q.enqueue) 
    xs.forall{_ == q.dequeue} 
    } 

    property("isEmpty always true after complete dequeue") = forAll {(xs: List[Int]) => 
    val q = new Queue[Int] 
    xs.foreach(q.enqueue) 
    xs.foreach(_ => q.dequeue) 
    q.isEmpty 
    } 
} 

build.sbt:

scalaVersion := "2.11.2" 

libraryDependencies ++= Seq(
    "org.scalacheck" %% "scalacheck" % "1.11.5" % "test" 
) 

結果:

$ sbt test 
[info] + Queue.enqueue never throws an exception: OK, passed 100 tests. 
[info] + Queue.dequeue always presents elements in FIFO order: OK, passed 100 tests. 
[info] + Queue.isEmpty always true after complete dequeue: OK, passed 100 tests. 
[info] Passed: Total 3, Failed 0, Errors 0, Passed 3 
[success] Total time: 2 s, completed 24/09/2014 9:28:10 PM 
+0

你能舉個例子嗎?這是一個完整的隊列類,我正在嘗試寫 http://introcs.cs.princeton.edu/java/43stack/Queue.java.html – 3ek 2014-09-23 16:28:01

+0

示例@ 3ek – Synesso 2014-09-25 10:41:22

+0

謝謝Synesso。這正是我所期待的。 – 3ek 2014-09-26 23:31:07