0

I have a method in my ADT that throws an IllegalArgumentException if the argument already exists in one of the data structures I have as a field. I wanted to test this case in my GraphTest.java file that stores my JUnit tests. I thought it might have been something like assertThrows but I'm not sure what arguments to pass. Here is the code for my method that throws the exception:

 public void addEdge(Node childNode, Node parentNode, String label) {
    for (Edge e : edgeSet) {
        if (e.equals(new Edge(childNode, parentNode, label))) {
            throw new IllegalArgumentException();
        }
    }
    edgeSet.add(new Edge(childNode, parentNode, label));
    if (hasNode(childNode.label)) {
        graph.get(childNode).add(new Edge(childNode, parentNode, label));
    } else if (hasNode(parentNode.label)) {
        graph.get(parentNode).add(new Edge(childNode, parentNode, label));
    } else {
        Set<Edge> temp = new HashSet<>();
        temp.add(new Edge(childNode, parentNode, label));
        graph.put(childNode, temp);
    }
}

Here is the code for the JUnit test so far:

 @Test
public void testAddEdge() {
 // Test throwing an IllegalArgumentException when two equal edges are added
    Graph.Edge edge3 = new Graph.Edge(child, parent, "e1");
    // this edge already exists within the graph so I want to test the exception
    // once i add it to the graph
}
Luqman
  • 21
  • 8
  • Since you want to test your `addEdge()`, I'm not sure why you constructed a new `Edge` in your test (because your `addEdge()` takes these arguments and constructs the `Edge` object on its own). I would suppose something like `assertThrows(IllegalArgumentException.class, ()->{yourGraph.addEdge(child, parent, "e1");} );` should work. – maloomeister May 12 '22 at 07:10
  • use assertThrows – xMilos May 12 '22 at 07:25

0 Answers0