Mockito测试使用java.lang.NullPointerException

问题描述 投票:0回答:2

我用Junit 4和Mockito创建了一个Spring Boot 2应用程序。当我测试一些方法。会有这样的例外:

位于sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)at的sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)的com.xxx.service.SurveyServiceTest.getSurveyList(SurveyServiceTest.java:41)中的java.lang.NullPointerException 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 )在org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)在org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)在org.junit.internal.runners。在org.junit的org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)的org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)中的statements.InvokeMethod.evaluate(InvokeMethod.java:17) .runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)在org.junit.runners.Pare ntRunner $ 3.run(ParentRunner.java:290)在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)在org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)在org.junit .runners.ParentRunner.access $ 000(ParentRunner.java:58)在org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)在org.junit.runners.ParentRunner.run(ParentRunner.java:363)在在org.mockito.runners.runners.StrictRunner.run的org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)中的org.mockito.internal.runners.DefaultInternalRunner $ 1.run(DefaultInternalRunner.java:79) (StrictRunner.java:39)org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)atg.junit.runner.JUnitCore.run(JUnitCore.java:137)at com.intellij.junit4.JUnit4IdeaTestRunner。在com.intellij.rt.exe.junit.JUnitStarter.prepare的com.intellij.rt.execution.junit.IdeaTestRunner $ Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)中的startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) StreamsAndStart(JUnitStarter.java:242)在com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

这是我的测试代码

@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);
    }
}

SUV而言service.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);
    }
}

survey repository.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.hml

<?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,但这个问题仍然存在。任何帮助都将被应用。

spring-boot junit nullpointerexception mockito
2个回答
2
投票

@MockBean是一个Spring注释,只有在创建一个使用SpringRunner运行的Spring启动集成测试时才有效。

你在这里有一个单元测试,用MockitoJUnitRunner运行,你只需要Mockito来创建你的模拟存储库。正确的注释是@Mock


0
投票

你应该这样做:

@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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.