在尝试用Junit和Mockito2测试方法时,我得到了NullPointerException。
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
@Test
public void testMethod(){
Application app=mock(Application.class);//line 2
assertEquals(true,app.methodToTest());
}
我在第 2 行收到一个空指针异常。 我正在使用 junit 4.8.1 和 mockito-all 2.0.2-beta .应用程序类具有带有参数JSONObject(org.json.JSONObject)
的构造函数
在为方法编写任何测试用例之前,您必须初始化MockitoAnnotations.initMocks
例如:
protected boolean mockInitialized = false;
@Before
public void setUp() {
if (!mockInitialized) {
MockitoAnnotations.initMocks(this);
mockInitialized = true;
}
}
希望这可以解决您的问题。 或提供您尝试为其编写测试用例的实际类代码。
正如我在想的那样,空指针异常是由于依赖项中的不匹配。使用以下依赖项解决了上述问题
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4-legacy -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-legacy</artifactId>
<version>1.6.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.4</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4-legacy -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-legacy</artifactId>
<version>1.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>1.7.1</version>
<scope>test</scope>
</dependency>