伙计们,我是 JUnit 测试的新手,并试图很好地掌握它,现在我正在为一个构造函数(用于创建有向图的有向图类)编写 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 否则测试通过。提前致谢
最佳答案
你应该有很多测试用例。 最好为每个异常(exception)都有一个。
您执行的每个测试都是不同的,应该区别对待。
一个很好的引用是:Junit Cookbook .
实际上我在您的代码中看到了一个错误。 在您的测试用例中,您可以如下 mock 协作者。我做了一个模拟,使用“mockito”模拟库在每次调用时返回不同的值。
你基本上需要这样的东西:
@Test(expected = IllegalArgumentException.class)
public void DigraphInThatThrowsExceptionForVertices() {
In in = Mockito.mock(In.class);
when(in.readInt()).thenReturn(-1);
Digraph G = new Digraph(in);
fail();
}
@Test(expected = IllegalArgumentException.class)
public void DigraphInThatThrowsExceptionForEdges() {
In in = Mockito.mock(In.class);
when(in.readInt()).thenReturn(10).thenReturn(-1);
Digraph G = new Digraph(in);
fail();
}
@Test
public void DigraphInThatDoesNotThrowException() {
In in = Mockito.mock(In.class);
when(in.readInt()).thenReturn(10).thenReturn(15);
Digraph G = new Digraph(in.readInt());
}
这样测试代码更干净且易于阅读。
关于java - JUnit 测试构造函数测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18967964/