Guys I am new to JUnit testing and trying to get a good grip on it, right now I am writing JUnit tests for a constructor (for Digraph Class that creates a directed graph) that throws IllegalArgumentException when it reads negative int value and creates a graph if everything is ok (number of node value) is greater than zero.
Digraph Class:
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");
}
Below is the test that I am trying to write:
@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){
}
}
How should I test both of the cases using one (or two) test cases? If there's no -ve value detected by "in" I get java.lang.AssertionError otherwise test passes. Thanks in advance