1

我正在尝试使用 scalacheck 测试一个 java 类。例如,我在 ...\src\main\java\ 中有一个类 Queue

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\test\scala\ 中有一个 Scala 测试类 QueueTest.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 示例,但仍不清楚。

任何建议,将不胜感激

4

1 回答 1

1

唯一可能的测试enque是调用它并确保不会引发异常。

如果这是我的任务,我会为 all 定义一个属性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
  }
}

构建.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
于 2014-09-22T01:23:31.607 回答