Graph { public Graph addEdge(Node<?> node, Node<?> adj) { Objects.requireNonNull(node, "Cannot attach an edge to a null node"); if (Objects.equals(node, adj)) { throw new IllegalArgumentException("Cannot connect a node to itself"); } register(node); register(adj); checkCircularDependency(node, adj); this.adj.get(node).add(adj); return this; }  Graph addLeaf(Node<?> node); Graph addEdges(Node<?> node, Collection<Node<?>> adjs); Graph addEdge(Node<?> node, Node<?> adj); Collection<Node<?>> resolve();  }
@Test public void shouldNotAllowToAddSelfAsDependency() { final Graph graph = new Graph(); final Node<String> node = new Node<>(String.class); try { graph.addEdge(node, node); fail("It should have thrown an IllegalArgumentException"); } catch (Exception e) { assertThat(e, instanceOf(IllegalArgumentException.class)); } }
@Test public void shouldDetectCircularDependencies() { final Graph graph = new Graph(); final Node<Integer> intNode = new Node<>(Integer.class); final Node<Float> floatNode = new Node<>(Float.class); try { graph.addEdge(intNode, floatNode).addEdge(floatNode, intNode); fail("It should have thrown a CircularDependencyException"); } catch (Exception e) { assertThat(e, instanceOf(CircularDependencyException.class)); } }