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.