【发布时间】:2020-07-25 20:41:25
【问题描述】:
目前我正在以以下两种方式设置基本的 JUnit 测试,当在我调用 c.add() 的行运行测试时,这两种方式都会给我空指针异常:
public class CalculatorTest {
Calculator c;
@BeforeEach
public void setUp() {
c = new Calculator();
}
@Test
public void testAdd() {
System.out.println("add");
int a = 0;
int b = 0;
int expResult = 0;
int result = c.add(a, b);
assertEquals(expResult, result);
}
....
第二种方式:
public class CalculatorTest {
static Calculator c;
public CalculatorTest() {
}
@BeforeAll
public static void setUpClass() {
c = new Calculator();
}
@Test
public void testAdd() {
System.out.println("add");
int a = 0;
int b = 0;
int expResult = 0;
int result = c.add(a, b);
assertEquals(expResult, result);
}
...
此链接:JUNIT Null Pointer Exception 建议我这样做是正确的,但我仍然收到空指针异常。
我的 pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>
<version>1.6.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
</project>
【问题讨论】:
-
您能否验证(通过在设置方法中设置断点)在执行测试之前调用了这些方法?
-
看起来这些方法根本没有被调用。我的第一个猜测是我可能混淆了 Junit4/5,但我确认我使用的是 5。为什么不调用它?
-
你确定你没有混淆 Junit4 和 Junit5 吗?你能从
@Test-方法中删除public-修饰符吗?如果测试未执行或抛出错误提示测试不公开,则使用 Junit4 引擎。 -
当我删除公共时没有运行测试,但现在我更困惑为什么当我的项目依赖项中引用 5.6.0 jar 并且我使用“import org. junit.jupiter.api.BeforeEach"
-
导入只是API。 JUnit 的版本取决于运行时加载的引擎。你能分享你的项目吗?你用maven吗?在这种情况下:
pom.xml应该足以诊断问题。
标签: java unit-testing junit junit5