开发者

Generating random test cases

I am working on a library and need to test it. There are several operations (as functions) defined in my class which can be called in any order by the client.

Operation1(param1, param2)
Operation2(param3)
.
.
.
OperationN(paramX, paramY, paramZ)

param1, param2 etc are integers/double

Now, I am thinking of writing a test code to randomize the execution of the operations, such that a sequence of M operation will be performed in random. Each time an operation is cal开发者_Python百科led, the parameters need to be random generated.

What is the best way to do this in Java.


Randomized tests seem attractive because they seem to allow you to avoid writing lots of separate tests. The problem is that you can never be sure that the random sequence will hit the edge cases, etc that are likely to fail. IMO they are not a substitute for well designed and implemented whitebox tests.

For cases like yours, I try to design a bunch of test helpers that to make it easy to construct the input data structures. For example a simple language + parser that allows me to express the input and expected output as text, either embedded in the unit testcases or as separate files.


You need an interface for the operation such as

public interface Operation {
  public void do();
}

Create for each operation you want to execute a class implementing the interface. The individual parameters can be passed to the constructor.

Then put all instances in a list of type operation, randomize it and iterate through it.

List<Operation> ops = new Vector<Operation>();
ops.add(new ...);
Collections.shuffle();
for (Operation o: ops) {
  o.do();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜