【问题标题】:Adding elements to string array String[] and testing the results in Junit将元素添加到字符串数组 String[] 并在 Junit 中测试结果
【发布时间】:2013-09-05 20:21:49
【问题描述】:

我正在学习 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(add5); 和 assertEquals(false, added5);)不打印任何内容。看起来测试类没有读取 added5 的值。我多次调试这个小代码但没有成功。请问有什么帮助吗?

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

【问题讨论】:

    标签: java unit-testing junit4 arrays


    【解决方案1】:

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

    if (getCurrentSize() >= count) {
    

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

    当你把num改成5时,原来的语句为真(因为5 >= 4),所以第五次插入成功。

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

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多