gpt4 book ai didi

java - JUnit:具有私有(private)字段的测试生成器

转载 作者:行者123 更新时间:2023-11-29 09:29:11 25 4
gpt4 key购买 nike

我是初学者,我在类的构造函数中遇到 JUnit 测试问题。

我要测试的类称为 IntSortedArray,如下所示:

public class IntSortedArray {

private int[] elements;
private int size;


public IntSortedArray() {
this.elements = new int[16];
this.size = 0;
}

public IntSortedArray(int initialCapacity) throws IllegalArgumentException {
if(initialCapacity < 0) {
throw new IllegalArgumentException("Error - You can't create an array of negative length.");
}
else {
elements = new int[initialCapacity];
size = 0;
}
}

public IntSortedArray(int[] a) {
elements = new int[a.length + 16];
for(int i = 0; i < a.length; i++)
elements[i] = a[i];
size = a.length;
insertionSort(elements);
}

//other code...

}

我使用 Eclipse 为 JUnit 创建了一个类:

public class IntSortedArrayUnitTest {

private IntSortedArray isa;

@Test
public void testConstructorArray16Elements() {
isa = new IntSortedArray();
int expected = 0;
for(int i: isa.elements) **<-- ERROR**
expected += 1;
assertEquals(expected, 16);
}

}

我开始编写一个测试类,目的是测试 IntSortedArray 类的所有方法,包括构造函数。

第一个方法 testConstructorArray16Elements() 想要测试第一个构建器。所以我想我会检查数组元素的创建是否正确完成,所以 for 循环会计算 elements 的长度并确保它是 16(根据需要)。

但 Eclipse 会(正确地)生成一个错误,因为 elementsprivate。我该如何解决这个错误?我不想放置 public 字段,如果可能的话,我想避免创建方法 public int[] getElements()

你有什么建议?

另一个问题:我可以用同一个方法做两个assert吗?一个用于测试数组的长度,另一个用于测试 size 是否为 0。

希望不要犯大错,第一次用JUnit。

PS:如何测试第二个构造函数?

非常感谢!

最佳答案

看起来你的类字段被声明为私有(private)的,但你试图从类外部访问。您需要在类中提供accessors 方法以使其可见:

private int[] elements;
private int size;
public static final int MAX = 16;

public int[] getElements() { ... }
public int getSize() { return size; }

然后你就可以写出下面的代码了:

isa = new IntSortedArray();
int expected = 0;
for(int i: isa.getElements()) {
expected += 1;
}
assertEquals(expected, IntSortedArray.MAX );

看起来你的构造函数已经为 16 个整数创建了一个数组,但没有用任何值初始化它。为此,您应该具有以下代码:

public IntSortedArray() {
this.elements = new int[MAX];
this.size = 0;
for (int i=0 ; i < MAX ;i++) {
elements[i] = i;
size++;
}
}

关于java - JUnit:具有私有(private)字段的测试生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com