Which strategy to build test data
I am new in the development world and i am wondering which are the best strategy to build consistent and coherent complex test data (I mean my POJ开发者_StackOverflow社区O are complex to fill) for Unit Testing?
I have heard about "Test Data Builder" but too little topic speak about it on the Net.
I often need to do exactly the same task. Fuzz testing is a suitable approach, though we should be careful to distinguish between raw fuzzers and smart fuzzers. A smart fuzzer differs from a normal fuzz tool (like zzuf) in that it produces data targeted to your application. Obviously in this case, you want a smart fuzzer.
To write a smart fuzzer, you'll need to extract those rules that represent "consistent and coherent" and have them as logic. Probably best to give an example. The Model
class below has some logic against it.
class Model {
// Should always be between 0 and 10
int a;
// Children
List<Model> children;
// Only true at the root
boolean isRoot;
}
We can write a test data builder for this by just codifying those rules.
class ModelGenerator {
private Random random;
// A seed is a good idea; you want your tests to be reproducible
public ModelGenerator(int seed) {
random = new Random(seed);
}
public Model arbitrary () {
return generateSingleItem(true);
}
private Model generateSingleItem(boolean isRoot) {
Model model = new Model();
model.isRoot = isRoot;
model.a = random.nextInt(10);
int childrenCount = random.nextInt(100);
model.children = new ArrayList<Model>(childrenCount);
for (int i=0;i<childrenCount;++i) {
model.children.add(generateSingleItem(false));
}
return model;
}
}
Now you can use the generator to create random (but predictable thanks to the seed) models for you to test assertions with.
This approach is very closely related to QuickCheck. There is a Java version available which provides a common interface (and more!) the kind of approach described above.
精彩评论