Reputation: 87
I am studying data structure with Java. I have to create a bag implementation. I used String[] array to do this and test the results in JUnit.
My class is:
public class BagImplementation {
private int num = 4;
private String[] thisBag = new String[num];
private int count =0;
public int getCount(){
return count;
}
public int getCurrentSize() {
return num;
}
public boolean add(String newEntry) {
if(getCurrentSize() >= count){
thisBag[count] = newEntry;
count++;
return true;
}else{
count++;
System.out.println("reaching");
return false;
}
}
}
My JUnit test class is:
import static org.junit.Assert.*;
import org.junit.Test;
public class BagImplementationTest {
@Test
public void test() {
BagImplementation thisBag = new BagImplementation();
String input1 = "hi";
Boolean added1 = thisBag.add(input1);
assertEquals(true, added1);
String input2 = "hi";
Boolean added2 = thisBag.add(input2);
assertEquals(true, added2);
String input3 = "hi";
Boolean added3 = thisBag.add(input3);
System.out.println(thisBag.getCount());
assertEquals(true, added3);
String input4 = "hi";
Boolean added4 = thisBag.add(input4);
assertEquals(true, added4);
String input5 = "hi";
Boolean added5 = thisBag.add(input5);
System.out.println(thisBag.getCount());
System.out.println(added5);
assertEquals(false, added5);
}
}
The JUnit test is supposed to pass since the first four tests must be true and the fifth one is false. However, my test fails because of the last assertion. Moreover, the print statements (System.out.println(added5); and assertEquals(false, added5);) do not print anything. It looks like the test class is not reading the value of added5.I debugged this little code many times with no success. Any help please?
Note: If I set the parameter num to 5 and the last assertion to "assertEquals(true, added5)", the test passes.
Upvotes: 0
Views: 2936
Reputation: 5187
In your add
function, you have the following if-condition:
if (getCurrentSize() >= count) {
where count
is originally 0
, and getCurrentSize()
returns the value of num
(which is 4
). The thing is, when you insert the fifth time, count
is 4, and this statement evaluates to true. If you want it to fail the fifth time, you need a >
instead of a >=
(so that when count
is 4, it'll evaluate to false)
When you change num
to 5
, the original statement is true (since 5 >= 4
), and so the fifth insert succeeds.
Side note: Your add
function as is (when num
is 4
) ought to be throwing a IndexOutOfBoundsException
right as it tries to insert the fifth time. The fix will also resolve this issue (since you won't be trying to add to thisBag[num]
, which is one off the end of the array). Again, when you change num
to 5, the array is big enough, and you do not get this exception.
Upvotes: 2