伙计们我是JUnit测试的新手,并试图抓住它,现在我正在为构造函数编写JUnit测试(用于创建有向图的Digraph类),它在读取时抛出IllegalArgumentException负int值,并且如果一切正常(节点值的数量)大于零,则创建一个图形。JUnit测试构造函数测试
有向图类:
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,否则测试通过。在此先感谢
csoroiu,所以有应该对每个异常进行单独测试?因为如果我不这样做,我会得到AssertionError! – user1569891
@ user1569891我更新了帖子,每个异常都需要一个方法。您可以模拟In类或创建一个为每个测试返回'Digraph'构造函数所需的值以根据需要执行该测试的值。 – Claudiu
使用'ExpectedException'更好,在这个测试中你不能验证异常抛出的位置。 – Tobb