我正在尝试使用scalacheck测试java类。 例如,我在... \ src \ main \ java \
中有一个类Queuepublic 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.scalaimport 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 :(得分: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