我正在用Java学习数据结构。我必须创建一个包实现。我使用 String[] 数组来执行此操作并在 JUnit 中测试结果。
我的类(class)是:
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;
}
}
}
我的 JUnit 测试类是:
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);
}
}
JUnit 测试应该会通过,因为前四个测试必须为 true,而第五个测试为 false。但是,由于最后一个断言,我的测试失败了。此外,打印语句(System.out.println(added5);和assertEquals(false,added5);)不打印任何内容。看起来测试类没有读取added5的值。我多次调试了这段小代码,但没有成功。有什么帮助吗?
注意:如果我将参数 num 设置为 5,并将最后一个断言设置为“assertEquals(true, added5)”,则测试通过。
最佳答案
在您的 add
函数中,您有以下 if 条件:
if (getCurrentSize() >= count) {
其中 count
最初为 0
,而 getCurrentSize()
返回 num
的值(即 4
)。问题是,当您第五次插入时,count
为 4,并且该语句的计算结果为 true。如果你想让它第五次失败,你需要一个 >
而不是 >=
(这样当 count
为 4 时,它'将评估为 false)
当您将 num
更改为 5
时,原始语句为 true(因为 5 >= 4
),因此第五次插入成功.
旁注:您的 add
函数按原样(当 num
为 4
时)应该抛出一个当它第五次尝试插入时,IndexOutOfBoundsException
就出现了。此修复还将解决此问题(因为您不会尝试添加到 thisBag[num]
,这是数组末尾的一个)。同样,当您将 num
更改为 5 时,数组足够大,并且您不会收到此异常。
关于java - 将元素添加到字符串数组 String[] 并在 Junit 中测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18645228/