Тест Мокито с java.lang.NullPointerException - PullRequest
0 голосов
/ 25 ноября 2018

Я создал приложение Spring Boot 2 с Junit 4 и Mockito.Когда я проверяю какой-то метод.будет исключение, подобное этому:

java.lang.NullPointerException в com.xxx.service.SurveyServiceTest.getSurveyList (SurveyServiceTest.java:41) в sun.reflect.NativeMethodAccessorImpl.invoke0 () в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lanke.ho.jj.jj.jj.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall (FrameworkMethod.java:50) в org.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:12) в org.junitMhora.rame.invokeExplosively (FrameworkMethod.java:47) в org.junit.internal.runners.statements.InvokeMethod.evaluate (InvokeMethod.java:17) в org.junit.runners.ParentRunner.runLeaf (ParentRunner.java: or32.gav.runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:78) в org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) в org.junit.runners.ParentRunner $ 3.run (ParentRunner.java:290) в org.junit.runners.ParentRunner $ 1.schedule (ParentRunner.java:71) в org.junit.unnersParentRunner.runChildren (ParentRunner.java:288) в org.junit.runners.ParentRunner.access $ 000 (ParentRunner.java:58) в org.junit.runners.ParentRunner $ 2.оценке (ParentRunner.java:268itg или в.runners.ParentRunner.run (ParentRunner.java:363) в org.mockito.internal.runners.DefaultInternalRunner $ 1.run (DefaultInternalRunner.java:79) в org.mockito.internal.runners.DefaultInternalRunner.run (DefaultInternalRunner.85) в org.mockito.internal.runners.StrictRunner.run (StrictRunner.java:39) в org.mockito.junit.MockitoJUnitRunner.run (MockitoJUnitRunner.java:163) в org.junit.runner.junCunit.java: 137) в com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs (JUnit4IdeaTestRunner.java:68) в com.intellij.rt.execution.junit.IdeaTestRunner $ Repeater.stavaRunner7) в com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart (JUnitStarter.java:242) в com.intellij.rt.execution.junit.JUnitStarter.main (JUnit *tarter.java:705 * 100) *

Вот мой тестовый код

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

Я ссылался на эту статью Mockito NullPointerException , но проблема все еще существовала.Любая помощь будет оценена.

Ответы [ 2 ]

0 голосов
/ 26 ноября 2018

Вы должны сделать это:

@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 голосов
/ 25 ноября 2018

@MockBean - это аннотация Spring, которая действует только в том случае, если вы создаете тест интеграции интеграции с Spring, запускаемый с SpringRunner.

У вас есть модульный тест, вы запускаете с MockitoJUnitRunner, и вы просто хотите, чтобы Mockito создал ваш репозиторий.Правильная аннотация - @Mock.

...