首页 > 解决方案 > InjectMocks 对象在单元测试中为空

问题描述

这是我第一次使用 Mockito 进行 junit 测试。我正面临@InjectMocks 中使用的服务的 NPE 问题。我查看了其他解决方案,但即使遵循它们,它也显示相同。这是我的代码。

@RunWith(MockitoJUnitRunner.class)

public class CustomerStatementServiceTests {

    @InjectMocks
    private BBServiceImpl bbService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);    

    }

/**
 *  This test is to verify SUCCESS response
 */

@Test
public void testSuccess() { 

    BBResponse response = bbService.processDetails(txs);
    assertEquals("SUCCESSFUL" ,response.getResult());
}
}

BBServiceImpl

@Service
public class BBServiceImpl implements BBService {

final static Logger log = Logger.getLogger(BBServiceImpl.class);



public BBResponse process(List<Customer> customers) { 
  // My business logic goes here
}
}

Pom.xml

        <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>2.23.4</version>
        <scope>test</scope>
    </dependency>




    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

我的“bbService”对象在这里为空

我在这里错过了什么吗?

标签: javajunitmockito

解决方案


在提供了额外信息的讨论之后,答案可以总结为junit4和之间的 Maven 配置问题junit5

java.lang.NullPointerException
at com.cts.rabo.CustomerStatementServiceTests.testSuccess(CustomerStatementServiceTests.java:83)
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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60) 
...

堆栈跟踪显示了junit5引擎的明确用法。

pom 还包括以下依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.2.5.RELEASE</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

在 Spring Boot 2.2.0.RELEASE 之前,spring-boot-starter-test 包含 junit4 依赖传递。从 Spring Boot 2.2.0 开始,Junit Jupiter 被包括在内。

根据这个答案,排除似乎阻止了执行。

删除排除为我解决了这个问题。


junit5如果没有明显的使用要求,我建议切换到junit4.

检查此答案以获取有关如何与mockito一起使用的更多信息junit5


推荐阅读