伙计们,我是 JUnit 测试的新手并试图很好地掌握它,现在我正在为构造函数(用于创建有向图的 Digraph 类)编写 JUnit 测试,当它读取负 int 值并创建图形时抛出 IllegalArgumentException如果一切正常(节点值的数量)大于零。
有向图类:
In in = new In();
public Digraph(In in) {
try {
this.nodes = in.readInt();
System.out.println("Total nodes in graph: "+ nodes);
if (nodes < 0) throw new IllegalArgumentException("Number of vertices must be > 0);
int E = in.readInt();
if (E < 0) throw new IllegalArgumentException("Number of edges must be >0);
}catch (NoSuchElementException e) {
throw new InputMismatchException("Invalid input format in Digraph constructor");
}
以下是我正在尝试编写的测试:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test(expected = IllegalArgumentException.class)
public void DigraphIn() {
Digraph G = new Digraph(in.readInt());
exception.expect(IllegalArgumentException.class);
exception.expectMessage("Vertices can't be nagative");
exception.expectMessage("Invalid input format in Digraph constructor");
exception.expectMessage("Number of edges in a Digraph must be nonnegative");
try{
}catch (AssertionError e){
}
}
我应该如何使用一个(或两个)测试用例来测试这两种情况?如果“in”没有检测到 -ve 值,我会得到 java.lang.AssertionError 否则测试通过。提前致谢