Reputation: 12469
I have got a tree-like structure based on the two following classes:
public class SchemaNode
{
private SchemaNode parentNode;
private String elementName;
private List<Edge> edges;
/* constructors, getters/setters, etc. omitted to improve brevity */
}
public class Edge
{
private int minCardinality;
private int maxCardinality;
private SchemaNode targetNode;
/* constructors, getters/setters, etc. omitted to improve brevity */
}
I have also created a builder to simplify generating the trees:
public class SchemaTreeBuilder
{
private SchemaNode result;
private SchemaNode currentNode;
public SchemaTreeBuilder(String nodeName) {
result = new SchemaNode(nodeName);
currentNode = result;
}
public SchemaTreeBuilder addEdge(int minCardinality, int maxCardinality, String elementName)
{
SchemaNode targetNode = new SchemaNode(elementName, currentNode);
Edge edge = new Edge(minCardinality, maxCardinality, targetNode);
currentNode.addEdge(edge);
currentNode = targetNode;
return this;
}
public SchemaTreeBuilder addEdge(String elementName) {
this.addEdge(1, 1, elementName);
return this;
}
public SchemaTreeBuilder up()
{
SchemaNode parentNode = currentNode.getParent();
if (parentNode == null) {
throw new IllegalStateException("Called up on a root node.");
}
currentNode = parentNode;
return this;
}
public SchemaNode getResult() {
return result;
}
}
Now I'd like to write some unit tests to ensure that the builder works properly. I have created the following beginning of a test:
@Test
public void buildsABasicSchemaTree()
{
SchemaNode tree =
new SchemaTreeBuilder("is")
.addEdge(1, 1, "people")
.addEdge(0, 100, "person")
.addEdge(1, 1, "id")
.up()
.addEdge(1, 1, "name")
.up()
.up()
.up()
.addEdge(1, 1, "courses")
.addEdge(1, 10, "course")
.addEdge(1, 1, "id")
.up()
.addEdge(1, 1, "teacher_id")
.up()
.addEdge(1, 1, "students")
.addEdge(1, 30, "student_id")
.getResult();
...
}
But I'm wondering what is the best way to express the assert statement to ensure that the tree was build properly.
Any other suggestions about how to improve the code (e.g. not related to the question) are appreciated as well. Please leave them in comments to the question.
Upvotes: 1
Views: 258
Reputation: 15028
Do you have any operations on the structure? It is common to test things based on properties of their operations. If you have a function that flattens the tree to a list and a function that counts the number of nodes in the tree, you can check that the list has as many elements as there are nodes in the tree. If you have a way to look up a particular element in the tree, make sure you are getting that element back.
If you have any other functions operating on the tree, try to come up with "laws" they should satisfy and test those laws!
The point of tests is not to exclude any possibility of an error whatsoever; the point of the tests is to verify integrity at enough different angles that an error is unlikely.
Upvotes: 1