Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我们如何测试数组返回的长度是否不同?_Java_Unit Testing_Junit - Fatal编程技术网

Java 我们如何测试数组返回的长度是否不同?

Java 我们如何测试数组返回的长度是否不同?,java,unit-testing,junit,Java,Unit Testing,Junit,我想用签名int[]myMethod(int[]array,int-removedElement)作为参数来测试一个方法。 如果元素在数组中,则该方法应移除该元素。因此,该方法可以使用array.length-1返回int[] assertarayequals()不确认返回的数组是否具有不同的长度 assertNotEquals()不合适,因为该方法可能会错误地删除多个元素 如何测试此方法?有两个方面可以断言: 数组的长度 数组的内容 的确,前者将被隐式测试,后者则被测试,但我更喜欢显式测试

我想用签名
int[]myMethod(int[]array,int-removedElement)
作为参数来测试一个方法。 如果元素在数组中,则该方法应移除该元素。因此,该方法可以使用
array.length-1
返回
int[]

assertarayequals()
不确认返回的数组是否具有不同的长度

assertNotEquals()
不合适,因为该方法可能会错误地删除多个元素


如何测试此方法?

有两个方面可以断言:

  • 数组的长度
  • 数组的内容
的确,前者将被隐式测试,后者则被测试,但我更喜欢显式测试

这样做很容易:存储输入的长度,并使用
assertEquals()
将其与输出进行比较


对于后者,您使用输入数组(
new[]{5,6}
)和输出(
new[]{5}
)并使用
assertarayequals()
将输出与方法的结果进行比较,给定输入和参数
6

,通过JUnit文档查看,我发现
assertEquals(long,long)
。您应该能够执行以下操作:

Assert.assertEquals("The array length is not what was expected!", (long) array.length - 1, (long) modifiedArray.length);
当然,假设您正在
modifiedArray
变量中保存修改后的数组


(我几乎没有JUnit方面的经验,所以我可能完全错了。如果我错了,让我知道。)

我仍然会使用ArrayAsertSequals进行测试,只需使用新的int[]{}创建您的输入和预期结果

@Test
public void shrinksArray() {
    assertArrayEquals(new int[] { 2, 3 }, remove(new int[] { 1, 2, 3 }, 1));
    assertArrayEquals(new int[] { 1, 2 }, remove(new int[] { 1, 2, 3 }, 3));
    assertArrayEquals(new int[] { 1, 3 }, remove(new int[] { 1, 2, 3 }, 2));
    assertArrayEquals(new int[] { 1, 2, 3 }, remove(new int[] { 1, 2, 3 }, 9));
}
或者如果您对每个测试的单个断言非常着迷

private static final int[] ORIGINAL = new int[] { 1, 2, 3 };

@Test
public void removesFromBeginning() {
    assertArrayEquals(new int[] { 2, 3 }, remove(ORIGINAL, 1));
}

@Test
public void removesFromEnd() {
    assertArrayEquals(new int[] { 1, 2 }, remove(ORIGINAL, 3));
}

@Test
public void removesFromMiddle() {
    assertArrayEquals(new int[] { 1, 3 }, remove(ORIGINAL, 2));
}

@Test
public void doesNotRemoveUnknownItem() {
    assertArrayEquals(ORIGINAL, remove(ORIGINAL, 9));
}

创建一个具有预期值的新数组,并使用
assertArrayEquals
将此预期数组与该方法的结果进行比较。如果您只想测试数组的长度,为什么不在
array.length()上使用
asserEquals
。但是,如果您想测试是否删除了正确的元素,那么Luiggis答案将有效现在有许多答案,请您检查它们,如果您的问题得到解决,请接受其中一个;在JUnit中,
assertSame
方法测试两个对象是否相同,因此此方法不适合使用。对于两个基本值的比较,
assertEquals
方法是合适的。@Arkanon…这是一个输入错误。它应该是
assertEquals()
。固定的。