Junit测试对于Java中的sumoverarray方法不起作用。

huangapple go评论97阅读模式
英文:

Junit test not working for sumoverarray method Java

问题

以下是您提供的代码的中文翻译:

我正在尝试运行一个针对我的sumoverarray方法的测试,但我不断收到一个断言错误的失败消息。以下是我的方法。

public class SumOverArray {

	public static int IterateAndSum(int[] arr) {
		int sum = 0;
		for (int i : arr) {
			sum = sum + i;
		}
		return sum;
	}
}

这是我的 JUnit 测试。

@Test
public void test3() {
    int[] arr = { 1, 2, 3 };
    assertNotEquals(0, SumOverArray.IterateAndSum(arr));
    try {
        SumOverArray.IterateAndSum(null);
        assertTrue(true);
    } catch (NullPointerException e) {
        fail();
    }
    int[] arr2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    assertEquals(78, SumOverArray.IterateAndSum(arr2));
    int[] arr3 = { -1, -2, -3, -4, -5, -6, -7, -8, -9 };
    assertEquals(-45, SumOverArray.IterateAndSum(arr3));
    int[] arr4 = { 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 };
    assertEquals(1095, SumOverArray.IterateAndSum(arr4));
}
英文:

I am trying to run a test for my sumoverarray method but I keep getting a failure saying AssertionError. Here's my method.

public class SumOverArray {

	public static int IterateAndSum(int[] arr) {
		int sum=0;
		for (int i:arr) {
			sum=sum+i;
		}
		return sum;
		
	}
}

Here is my junit test

@Test
    public void test3() {
        int[] arr = { 1, 2, 3 };
        assertNotEquals(0, SumOverArray.IterateAndSum(arr));
        try {
            SumOverArray.IterateAndSum(null);
            assertTrue(true);
        } catch (NullPointerException e) {
            fail();
        }
        int [] arr2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
        assertEquals(78, SumOverArray.IterateAndSum(arr2));
        int[] arr3 = { -1, -2, -3, -4, -5, -6, -7, -8, -9 };
		assertEquals(-45, SumOverArray.IterateAndSum(arr3));
		int[] arr4 = { 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80 };
		assertEquals(1095, SumOverArray.IterateAndSum(arr4));

    }

答案1

得分: 3

以下是翻译好的内容:

行为是符合预期的。查看测试方法的第二部分:

try {
    SumOverArray.IterateAndSum(null);
    assertTrue(true);
} catch (NullPointerException e) {
    fail();
}

我们调用 SumOverArray.IterateAndSum 方法并传递 null,期望不会抛出 NullPointerException 异常。但是从实现来看,在方法 SumOverArray.IterateAndSum 中我们并没有进行 null 检查,因此尝试迭代遍历 null。这最终导致抛出了 NullPointerException 异常。测试中的 catch 块会被执行,从而测试失败。

如果这个测试通过,所有其他测试也会通过。

如果我们想要断言在将 null 作为参数传递时会抛出 NullPointerException 异常,可以使用 Assertions.assertThrows(...) 方法:

final NullPointerException exception = assertThrows(
    NullPointerException.class,
    () -> SumOverArray.IterateAndSum(null));
// 在必要时在这里验证异常

对代码的一些备注:

  • 在 Java 中,方法名应该始终以小写字母开头(IterateAndSum -> iterateAndSum
  • 一个测试应该只测试一件事情。因此,上面的一个测试方法应该被拆分成四个测试。
  • 最后三个测试是多余的,其中一个就足够了。
  • 显式调用 fail() 来处理异常是多余的,可以省略。
  • 从语义上讲,第一个测试也被最后三个测试所覆盖。因此,这个测试也是多余的。
  • 我建议在参数为 null 时定义一个要返回的值,选择 0 似乎是合理的。

这样,我们就得到了以下两个测试:

@Test
@DisplayName("如果参数为 null,则应返回 0")
public void shouldReturnZerofNullIsPassedAsParameter() {
    // GIVEN:无特定前提条件

    // WHEN
    final int actual = SumOverArray.iterateAndSum(null);

    // THEN
    assertEquals(0, actual);
}

// 替代测试,如果我们想要确保传递 null 时会抛出 NPE
@Test
@DisplayName("如果参数为 null,则应抛出 NullPointerException")
public void shouldThrowNullPointerExceptionIfNullIsPassedAsParameter() {
    // GIVEN:无特定前提条件

    // WHEN & THEN
    assertThrows(
        NullPointerException.class,
        () -> SumOverArray.iterateAndSum(null));
}

@Test
@DisplayName("如果将 1、2、...、12 相加,则应返回 78")
void shouldReturnCorrectResult() {
    // GIVEN
    final int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

    // WHEN
    final int actual = SumOverArray.iterateAndSum(arr);

    // THEN
    assertEquals(78, actual);
}
英文:

The behaviour is expected. Looking at the second part of the test method:

try {
    SumOverArray.IterateAndSum(null);
    assertTrue(true);
} catch (NullPointerException e) {
    fail();
}

We call SumOverArray.IterateAndSum with null and expect no NullPointerException to be thrown. But looking at the implementation, we do not perform a null-check in method SumOverArray.IterateAndSum and thus try to iterate over null. This, ultimately, leads to a NullPointerException to be thrown. The catch-block in the test is entered and the test fails.

All other tests would pass, if this test would pass.

<kbd>Ideone demo</kbd>

If we, however, want to assert that a NullPointerException is thrown when null is passed as parameter, then we can use Assertions.assertThrows(...):

final NullPointerException exception = assertThrows(
    NullPointerException.class,
    () -&gt; SumOverArray.IterateAndSum(null));
// validate exception here if necessary

Some remarks on the code:

  • Method names in Java should always start with a lowercase letter (IterateAndSum -> iterateAndSum)
  • A test should test one thing and one thing only. Thus, the one test method above should be written as four tests.
  • The last three tests are redundant, one of them is sufficient.
  • The explicit fail() on an exception is superfluous and can be omitted.
  • Semantically, the first test is also covered by the last three tests. Thus this test is also redundant.
  • I would suggest to define a value to return if null is passed as argument, 0 seems sensible.

This leaves us with the following two tests:

@Test
@DisplayName(&quot;should return 0 if null is passed as argument&quot;)
public void shouldReturnZerofNullIsPassedAsParameter() {
    // GIVEN: nothing

    // WHEN
    final int actual = SumOverArray.iterateAndSum(null);

    // THEN
    assertEquals(0, actual);
}

// Alternative test, if we want to assure that a NPE is thrown if null is passed
@Test
@DisplayName(&quot;should throw NPE if null is passed as argument&quot;)
public void shouldThrowNullPointerExceptionIfNullIsPassedAsParameter() {
    // GIVEN: nothing

    // WHEN &amp; THEN
    assertThrows(
        NullPointerException.class,
        () -&gt; SumOverArray.iterateAndSum(null));
}

@Test
@DisplayName(&quot;should return 78 if 1, 2 , ... , 12 are summed&quot;)
void shouldReturnCorrectResult() {
    // GIVEN
    final int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

    // WHEN
    final int actual = SumOverArray.iterateAndSum(arr);

    // THEN
    assertEquals(78, actual);
}

huangapple
  • 本文由 发表于 2020年9月3日 03:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63712678.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定