我有一个基于以下两个类的树状结构:
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 */
}
我还创建了一个构建器来简化生成树:
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;
}
}
现在我想编写一些单元测试来确保构建器正常工作。我创建了以下测试的开头:
@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();
...
}
但我想知道表达断言语句以确保正确构建树的最佳方式是什么。
关于如何改进代码(例如与问题无关)的任何其他建议也值得赞赏。请在对问题的评论中留下它们。