有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java向字符串数组string[]添加元素并在Junit中测试结果

我正在用Java学习数据结构。我必须创建一个包实现。我使用String[]数组来完成这项工作,并在JUnit中测试结果

我的班级是:

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测试应该通过,因为前四个测试必须为真,第五个测试为假。然而,由于最后一个断言,我的测试失败了。此外,打印语句(System.out.println(added5);和assertEquals(假,加5);)不要打印任何东西。看起来测试类没有读取added5的值。我多次调试这个小代码都没有成功。需要帮忙吗

注意:如果我将参数num设置为5,并将最后一个断言设置为“assertEquals(true,added5)”,则测试通过


共 (1) 个答案

  1. # 1 楼答案

    add函数中,有以下if条件:

    if (getCurrentSize() >= count) {
    

    其中count最初是0,而getCurrentSize()返回num(即4)的值。问题是,当你第五次插入时,count是4,这个语句的计算结果是true。如果希望它第五次失败,则需要一个>而不是一个>=(这样当count为4时,它的计算结果将为false)

    当您将num更改为5时,原始语句为true(因为5 >= 4),因此第五次插入成功

    旁注:您的add函数(当num4)应该在第五次尝试插入时正确抛出IndexOutOfBoundsException。该修复程序还将解决这个问题(因为您不会尝试添加到thisBag[num],这是数组末尾的一个)。同样,当您将num更改为5时,数组足够大,并且不会出现此异常