【问题标题】:Why does a NullPointerException error appear for ArrayList.java when my code doesn't use an ArrayLIst?当我的代码不使用 ArrayLIst 时,为什么 ArrayList.java 会出现 NullPointerException 错误?
【发布时间】:2020-03-04 05:00:16
【问题描述】:

所以我有 2 段 Java 代码。一个是一小段简单的源代码,另一个是我试图弄乱的 JUnit 测试类。但是,每当我想调试代码以确保此简单代码正确显示时,我都会在 java.util.ArrayList.forEach(ArrayList.java:1507) 错误处收到 NullPointerException。

这是我的源代码:

public class sourceCode {
    public int mid(int x, int y, int z) {
        int m = z;

        if (y < z) {
            if (x < y) {
                m = y;
            }
            else if (x < z) {
                m = x;
            }
        }
        else {
            if (x > y) {
                m = y;
            }
            else if (x > z) {
                m = x;
            }
        }
        return m;
    }

}

这是我的 JUnit 测试用例代码:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.Before;
import org.junit.jupiter.api.Test;

public class sourceCodeTest {
      public sourceCode sourceCodeVar;

      //Test Fixture
      @Before
      public void setUpBeforeClass() throws Exception {
            sourceCodeVar = new sourceCode();
      }

      @Test
      void test() {
          //Test Oracle
          int oracle = 2;
          //Test Case
          int middleTest1 = sourceCodeVar.mid(1, 2, 3);
          assertEquals(oracle, middleTest1);
      }

}

调查结果

它们都是同一目录下的不同文件,它们也是在 Eclipse 中的一个项目中创建的。我在另一个稍微相关的线程中看到它可能是与 Eclipse 相关的错误,但是在 VS Code 上对其进行测试时,出现了相同的错误,这表明这是我的错误。

我想我之所以如此困惑的原因是代码似乎很简单,以至于我无法确定我搞砸的地方。

【问题讨论】:

  • 请提供证据。堆栈跟踪。

标签: java unit-testing testing arraylist junit


【解决方案1】:

您的测试代码中似乎同时混合了 JUnit-4JUnit-5

import org.junit.Before;            // <- Junit-4 annotation
import org.junit.jupiter.api.Test;  // <- Junit-5 annotation

当您使用Junit-5 进行测试时,最好使用所有Junit-5 注释。将@Before 替换为org.junit.jupiter.api.BeforeEach -> @BeforeEach

您的代码应如下所示:

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class sourceCodeTest {
      public sourceCode sourceCodeVar;

      // change:
      @BeforeEach
      public void setUpBeforeClass() throws Exception {
            sourceCodeVar = new sourceCode();
      }

      @Test
      void test() {
          //Test Oracle
          int oracle = 2;
          //Test Case
          int middleTest1 = sourceCodeVar.mid(1, 2, 3);
          assertEquals(oracle, middleTest1);
      }

}

更多信息请查看DOCUMENTATION:

@BeforeEach

表示被注解的方法应该在当前类中的每个@Test、@RepeatedTest、@ParameterizedTest或@TestFactory方法之前执行;类似于 JUnit 4 的 @Before。除非被覆盖,否则此类方法会被继承。

【讨论】:

  • 看来是对的!令人难以置信的是,我没有收到更直接的错误消息,告诉我我混淆了 JUnit 4 和 5,但这确实清除了它。文档再次节省了时间。非常感谢
猜你喜欢
  • 2015-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多