简体   繁体   English

使用Mockito模拟类时出现NullPointerException

[英]NullPointerException while mocking a class with Mockito

While trying to test a method with Junit and Mockito2 , I am getting NullPointerException . 尝试使用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());
    }

I am getting a NullPointerException on line 2 . 我在第2行上收到NullPointerException。 I am using junit 4.8.1 and mockito-all 2.0.2-beta .The Application class has constructor with Argument JSONObject(org.json.JSONObject) 我正在使用junit 4.8.1和mockito-all 2.0.2-beta JSONObject(org.json.JSONObject)类具有带有参数JSONObject(org.json.JSONObject)构造函数

Before writing any test cases for methods you have to initialized MockitoAnnotations.initMocks eg: 在为方法编写任何测试用例之前,您必须初始化MockitoAnnotations.initMocks例如:

protected boolean mockInitialized = false;
@Before
public void setUp() {
   if (!mockInitialized) {
      MockitoAnnotations.initMocks(this);
      mockInitialized = true;
   }
}

Hope this may resolve your issue. 希望这可以解决您的问题。 or provide the actual class code for which you are trying to write test cases. 或提供您要为其编写测试用例的实际类代码。

As I was thinking , the nullpointerexception was due to mismatches in dependencies . 正如我在想的那样,nullpointerexception是由于依赖项不匹配所致。 The mentioned issue got resolved by using below dependencies 通过使用以下依赖项解决了上述问题

<!-- 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM