I need to implement a sparse graph and do some junit tests on it.
This is my graph class:
package graphs;
import java.util.Collection;
import java.util.HashMap;
public class SparseGraph<V, E> implements Graph<V, E> {
HashMap<V, HashMap<V, E>> node;
public SparseGraph() {
node = new HashMap<>();
}
@Override
public boolean addVertex(V vertex) {
if (hasVertex(vertex)) {
return false;
}
else {
node.put(vertex, new HashMap());
}
return true;
}
@Override
public boolean addEdge(V vertex1, V vertex2, E data) {
if (!hasVertex(vertex1) || !hasVertex(vertex2)) {
return false;
}
if (hasEdge(vertex1, vertex2) && getData(vertex1, vertex2).equals(data)) {
return false;
}
else if (hasEdge(vertex1, vertex2) && !getData(vertex1, vertex2).equals(data)) {
node.get(vertex1).put(vertex2, data);
return true;
}
else {
(node.get(vertex1)).put(vertex2, data);
}
return true;
}
@Override
public boolean hasVertex(V vertex) {
if (vertex == null) return false;
return (node.containsKey(vertex));
}
@Override
public boolean hasEdge(V vertex1, V vertex2) {
if (!hasVertex(vertex1) || !hasVertex(vertex2)) return false;
if (node.get(vertex1).containsKey(vertex2)) {
return true;
}
return false;
}
@Override
public E getData(V vertex1, V vertex2) {
if (!hasVertex(vertex1) || !hasVertex(vertex2)) return null;
return node.get(vertex1).get(vertex2);
}
@Override
public Collection<V> getVertices() {
return node.keySet();
}
@Override
public Collection<V> getNeighbors(V vertex) {
if (!hasVertex(vertex))
return null;
else
return node.get(vertex).keySet();
}
}// end class
and this is my test:
public void testGetVertices() {
SparseGraph instance = new SparseGraph();
instance.addVertex("A");
instance.addVertex("B");
instance.addVertex("C");
instance.addVertex("D");
instance.addVertex("E");
//assertEquals("[D, E, A, B, C]",instance.getVertices());
}
My question is, how can I create a test that checks if all vertices are present in my Collection?
I tried comparing a string with the keySet, but the error was that is expected a string but method assertEquals gets a keySet.
There are many ways of testing this. The most basic one is to do a contains for each element but JUnit has more elegant ways. You can use assertThat() together with the Hamcrest
use following imports: