I am trying to write unit tests for a BinarySearchTree
class
The keys()
return an Iterable
.It uses another class called Queue
in which the keys are enqueued and returned..
The Queue (third party class) however doesn't have any equals() defined.
public class BinarySearchTree<Key extends Comparable<Key>,Value> {
Node root ;
private class Node{
private Key key;
private Value val;
private Node left;
private Node right;
private int N;
public Node(Key k, Value v,int N) {
super();
this.key = k;
this.val = v;
this.N = N;
}
}
public Iterable<Key> keys(){
Queue<Key> q = new Queue<Key>();
inOrder(root,q);
return q;
}
private void inOrder(Node x,Queue q){
if(x == null)return;
inOrder(x.left,q);
q.enqueue(x.key);
inOrder(x.right,q);
}
...
}
trying to write unit test
@Test
public void testKeys(){
MyBST<String, Integer> st = new MyBST<String, Integer>();
st.put("S",7);
st.put("E",2);
st.put("X",8);
st.put("A",3);
st.put("R",4);
st.put("C",1);
st.put("H",5);
st.put("M",6);
Queue<String> q = new Queue<String>();
q.enqueue("A");
q.enqueue("C");
q.enqueue("E");
q.enqueue("H");
q.enqueue("M");
q.enqueue("R");
q.enqueue("S");
q.enqueue("X");
Iterable<String> actual = st.keys();
assertEquals(q,actual);
}
This fails
java.lang.AssertionError: expected: std.Queue<A C E H M R S X > but was: std.Queue<A C E H M R S X >
at org.junit.Assert.fail(Assert.java:93)
at org.junit.Assert.failNotEquals(Assert.java:647)
at org.junit.Assert.assertEquals(Assert.java:128)
at org.junit.Assert.assertEquals(Assert.java:147)
at week4.MyBSTTests.testKeys(BSTTests.java:304)
Do I have to implement an equals() in the third party class or is there any other way to do this to check equality? All I could think of was running a loop dequeueing from queue q and comparing it with what the iterator returned.I am not sure if there is a better way.. Please advise..
Iterable<String> actual = st.keys();
Iterator<String> actualit = actual.iterator();
while(actualit.hasNext()){
String actualkey = actualit.next();
String exp = q.dequeue();
assertEquals(actualkey,exp);
}
Use Hamcrest's Matchers.contains
(described here). For example:
assertThat(queue1.keys(), Matchers.contains("A", "C", "E", "H", "M", "R", "S", "X"));
This will check the elements that the Iterable
returns without needing equality implemented on your queue class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With