题目链接
该题目主要是训练java的泛型编程、AF(抽象函数) 、rep invariants(表示不变量)、mutable、immutable数据类型和preventing rep exposure(防御式编程)
ConcreteEdgesGraph和ConcreteVerticesGraph最大的区别在于EDGE类是immutable而Vertices类是mutable。
首先先编写关于Graph的测试函数GraphInstanceTest他其实是后面的编写的ConcreteEdgesGraphTest和ConcreteVerticesGraphTest的父类。
所以我们编写的GraphInstanceTest测试函数可以分为以下几种类型:
- 测试add函数 按加入的点分类:点已存在,点不存在(重复输入)
@Test
public void testAdd(){
//Graph<String>
Graph<String> test1=emptyInstance();
String a="xu";
String b="ya";
test1.add(a);
test1.add(b);
assertEquals(true,test1.vertices().contains(a));
assertEquals(true,test1.vertices().contains(b));
assertEquals(false,test1.add(a));
}
2.测试set函数
观察set函数的spec 可将测试划分为边已经存在,传入权值为0,移除边。传入权值大于0,更新边,返回原有边权值。传入权值小于0,return -1。边不存在,传入权值大于等于0加入顶点return 0,边不存在,传入权值小于0 return -1。
@Test
public void testset(){
Graph<String> graph =emptyInstance();
assertEquals(0,graph.set("a", "b", 5));
assertEquals(0,graph.set("b", "c", 4));
assertEquals(5,graph.set("a", "b", 6));
assertEquals(6,graph.set("a", "b", 0));
assertEquals(0,graph.set("a", "c", 0));
assertEquals(-1,graph.set("a", "b", -3));
}
3.测试remove
@Test
public void testRemove() {
Graph<String> test3=emptyInstance();
test3.add("x");
//test3.add();
assertEquals(true,test3.vertices().contains("x"));
test3.remove("x");
assertEquals(false,test3.vertices().contains("x"));
}
4.测试vertices
//两种情况:空图,不是空图
@Test
public void testVertices() {
testAdd();
Graph<String> graph =emptyInstance();
String a="a";
String b="b";
String c="c";
graph.add(a);
graph.add(b);
graph.add(c);
assertEquals(true,graph.vertices().contains(a));
assertEquals(true,graph.vertices().contains(b));
assertEquals(true,graph.vertices().contains(c));
}
5.测试soureces
//两种情况:边已经存在,边不存在
@Test
public void testSources() {
testAdd();
testset();
Graph<String> graph =emptyInstance();
String a="a";
String b="b";
String c="c";
graph.add(a);
graph.add(b);
graph.add(c);
graph.set(a, b, 5);
graph.set(b, c, 4);
graph.set(a, c, 3);
Map<String,Integer> map=new HashMap<String,Integer>();
map.put(a,3);
map.put(b,4);
assertEquals(map,graph.sources(c));
}
6.测试targets
//两种情况:边已经存在,边不存在
@Test
public void testTargets() {
testAdd();
testset();
Graph<String> graph =emptyInstance();
String a="a";
String b="b";
String c="c";
graph.add(a);
graph.add(b);
graph.add(c);
graph.set(a, b, 5);
graph.set(b, c, 4);
graph.set(a, c, 3);
Map<String,Integer> map=new HashMap<String,Integer>();
map.put(c,3);
map.put(b,5);
assertEquals(map,graph.targets(a));
}