0
votes

I created a Spring Boot 2 application with Junit 4 and Mockito. When I test some method. there will be an exception like this :

java.lang.NullPointerException at com.xxx.service.SurveyServiceTest.getSurveyList(SurveyServiceTest.java:41) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79) at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85) at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39) at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Here is my test code

@RunWith(MockitoJUnitRunner.class)
public class SurveyServiceTest {

    @MockBean
    SurveyRepository repostory;

    @InjectMocks
    SurveyService service;

    @Test
    public void getSurveyList() {
        when(repostory.findAll()).thenReturn(Arrays.asList( new Survey(new Long(1),101,"Test1"),
                new Survey(new Long(2),102,"Test2")  ));
        assertTrue(service.getSurveyList().size() >0);
    }
}

SuveryService.java

@Service
public class SurveyService {
    @Autowired
    private SurveyRepository repostory;

    public List<Survey> getSurveyList() {
        return repostory.findAll();
    }

    public Optional<Survey> getSurveyById() {
        return repostory.findById((long) 1);
    }

    public Survey add() {
        Survey survey = new Survey();
        survey.setSurveyID(1);
        survey.setSurveyContent("ddddd");

        return repostory.save(survey);
    }

    public Survey update() {
        Survey survey = new Survey();
        survey.setSurveyID(1);
        survey.setSurveyContent("gggg1");
        return repostory.save(survey);
    }

    public void delete() {
        repostory.deleteById((long) 1);
    }

    public List<Survey> findBySurveyContent() {
        return repostory.findBySurveyContent("gggg1");
    }

    public int updateBySurveyId(){
        return repostory.updateBySurveyId("hhhhhh", 1);
    }
}

SurveyRepository.java

    public interface SurveyRepository  extends JpaRepository<Survey, Long> {

    public List<Survey> findBySurveyContent(String surveyContent);

    @Query(value = "update XXX_DATA.SURVEYS set SURVEYCONTENT=? where SURVEYID=?",nativeQuery = true)  
    @Modifying
    @Transactional
    public int updateBySurveyId(String surveyContent,int surveyId);
}

Survey.java

@Entity
@Table(name="SURVEYS", schema="XXX_DATA")
public class Survey{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")  
    private Long id; 

    @Column(name = "SURVEYID")  
    private Integer surveyID;

    @Column(name = "SURVEYCONTENT")  
    private String surveyContent;

    public Survey(){

    }

    public Survey(Long id,Integer surveyID,String surveyContent){
        this.id = id;
        this.surveyID = surveyID;
        this.surveyContent = surveyContent;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Integer getSurveyID() {
        return surveyID;
    }

    public void setSurveyID(Integer surveyID) {
        this.surveyID = surveyID;
    }

    public String getSurveyContent() {
        return surveyContent;
    }

    public void setSurveyContent(String surveyContent) {
        this.surveyContent = surveyContent;
    }
}

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.xxx.test</groupId>
<artifactId>xxx-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<name>xxx-service</name>
<description>XXX Service</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<repositories>
    <repository>
        <id>maven-repository</id>
        <url>file:///${project.basedir}/maven-repository</url>
    </repository>
    <repository>
        <id>com.ibm.db2.jcc</id>
        <url>https://artifacts.alfresco.com/nexus/content/repositories/public/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>com.ibm.db2.jcc</groupId>
        <artifactId>db2jcc4</artifactId>
        <version>10.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.ibm.watson.developer_cloud</groupId>
        <artifactId>java-sdk</artifactId>
        <version>5.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
     </dependency>
     <dependency>
        <groupId>com.ibm.swat.password</groupId>
        <artifactId>cwa2</artifactId>
        <version>2.3.5.3</version>
      </dependency>
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.15</version>
      </dependency> 
      <dependency> 
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.15</version>
      </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                  <skip>true</skip>
                </configuration>
        </plugin>
    </plugins>
</build>

I referenced this article Mockito NullPointerException, but the issue still existed. Any help will be appcirated.

3

3 Answers

2
votes

@MockBean is a Spring annotation, which only has an effect if you create a Spring boot integration test, run with the SpringRunner.

You have a unit test here, run with MockitoJUnitRunner, and you just want Mockito to create your mock repository. The correct annotation is @Mock.

0
votes

You sould do that :

@RunWith(MockitoJUnitRunner.class)
public class SurveyServiceTest {

    @Mock// and not MockBean
    SurveyRepository repostory;

    @InjectMocks
    SurveyService service;

    @Test
    public void getSurveyList() {
        when(repostory.findAll()).thenReturn(Arrays.asList( new Survey(new Long(1),101,"Test1"),
                new Survey(new Long(2),102,"Test2")  ));
        assertTrue(service.getSurveyList().size() >0);
    }
}
0
votes

To extend the above answers, Since @MockBean is a spring annotation, you can use the below code as an alternative. @MockBean is used to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. So it is a kind of functionality of both @Mock as well as @InjectMock. Also if you not following JUnit 5 you require to replace @RunWith(SpringRunner.class) with @ExtendWith(SpringExtention.class)

@RunWith(SpringRunner.class)
public class SurveyServiceTest {

    @MockBean
    SurveyRepository repostory;

    @Test
    public void getSurveyList() {
        when(repostory.findAll()).thenReturn(Arrays.asList( new Survey(new 
         Long(1),101,"Test1"),
            new Survey(new Long(2),102,"Test2")  ));
         assertTrue(service.getSurveyList().size() >0);
}

}