简体   繁体   English

Mockito @Mock 和@InjectMocks 是 null

[英]Mockito @Mock and @InjectMocks are null

I am trying to test this (anonymized) code:我正在尝试测试此(匿名)代码:

import org.springframework.stereotype.Service;

import java.time.LocalDate;
import com.dummy.domain.dummy.dao.MatchDAO;

@Service
public class TeamService {

    private MatchDAO matchDAO;

    public TeamService(MatchDAO matchDAO) {
        this.matchDAO = matchDAO;
    }

    public Team get(int teamId) {
        return get(teamId, LocalDate.now());
    }

    public Team get(int teamId, LocalDate date) {
        matchDAO.findMatchIdsForTeam(teamId, date);
        ...
    }
}

Using the following test code:使用以下测试代码:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.LocalDate;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class TeamServiceTest {
    @Mock
    MatchDAO matchDAO;

    @InjectMocks
    TeamService teamService;

//    @BeforeAll
//    public void createMocks() {
//        MockitoAnnotations.initMocks(this);
//    }

    @Test
    public void testGetTeam() {
        when(matchDAO.findMatchIdsForTeam(anyInt(), any(LocalDate.class))).thenReturn(new int[]{1234, 5678});

        Team team = teamService.get(1);
        ... assertions
    }
}

But I keep getting either this error:但我不断收到此错误:

[ERROR] com.dummy.domain.dummy.TeamServiceTest.testGetTeam()  Time elapsed: 0 s  <<< FAILURE!
java.lang.NullPointerException: Cannot invoke "com.dummy.domain.dummy.TeamService.get(int, java.time.LocalDate)" because "this.TeamService" is null

Or this error:或者这个错误:

[ERROR] com.dummy.domain.dummy.TeamServiceTest.testGetTeam()  Time elapsed: 0 s  <<< FAILURE!
java.lang.NullPointerException: Cannot invoke "com.dummy.domain.dummy.dao.MatchDAO.findMatchIdsForTeam(int, java.time.LocalDate)" because "this.TeamService" is null

Some tests give the error that @InjectMocks object is null and some tests give the error that the @Mock is null.一些测试给出的错误是@InjectMocks object 是 null,而一些测试给出的错误是@Mock 是 null。

I tried it with the @BeforeAll enabled and disabled (and also as @BeforeEach).我在启用和禁用@BeforeAll(以及@BeforeEach)的情况下进行了尝试。 I also tried with SpringExtension instead of MockitoExtension.我还尝试使用 SpringExtension 而不是 MockitoExtension。 I have also tried many suggestions including all stated in this post: mock instance is null after mock annotation我也尝试了很多建议,包括这篇文章中提到的所有建议: mock instance is null after mock annotation

Interestingly when running this test in maven it fails but when I try to run it in my IDE (Intellij) it is succesful.有趣的是,当在 maven 中运行此测试时,它失败了,但是当我尝试在我的 IDE (Intellij) 中运行它时,它是成功的。 I checked and both are using the same JDK and maven version.我检查过,两者都使用相同的 JDK 和 maven 版本。 Running it in our build pipeline is also giving the same error as local maven build.在我们的构建管道中运行它也会给出与本地 maven 构建相同的错误。

Can anyone help with this problem?谁能帮忙解决这个问题?

For reference this is my pom.xml作为参考,这是我的 pom.xml

<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.dummy.domain</groupId>
    <artifactId>dummy</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Update: The xml has a parent pom with the following content: (Updated based on @khmarbaise comment)更新:xml 有一个包含以下内容的父 pom:(根据@khmarbaise 评论更新)

<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
    <maven-surefire-plugin.version>3.0.0-M8</maven-surefire-plugin.version>
    <junit-jupiter.version>5.9.1</junit-jupiter.version>
    <lombok.version>1.18.24</lombok.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <scope>import</scope>
            <type>pom</type>
            <version>3.0.1</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                            <version>${lombok.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

In the end, I fixed the issue myself.最后,我自己解决了这个问题。 I replaced the dependencies on junit-jupiter-api , spring-boot-test , spring-test , and mockito-junit-jupiter with a dependency on spring-boot-starter-test .我用对spring-boot-starter-test的依赖替换了对junit-jupiter-apispring-boot-testspring-testmockito-junit-jupiter的依赖。 Even though the starter is using the same dependencies with the same versions I explicitly used, it did fix it.尽管启动器使用与我明确使用的相同版本相同的依赖项,但它确实修复了它。

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

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