java - 单元测试模拟服务实现

标签 java spring unit-testing spring-boot mockito

我在 spring boot 应用程序中也有一个服务和 serviceImpl。当我想测试它并尝试在 junit 测试类中模拟我的服务时,我遇到了 NullPointerException 错误。

这是我的服务实现

package com.test;

import java.util.Date;

public class MyServiceImpl implements MyService {
    @Override
    public MyObject doSomething(Date date) {
        return null;
    }
}

这是我的测试类

package com.test;

import com.netflix.discovery.shared.Application;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertNull;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
class MyServiceImplTest {

    @Mock
    MyService myservice;

    @Test
    void doSomethingTest() {
        assertNull(myservice.doSomething(null));
    }
}

最佳答案

当使用 @Mock 注解时,你需要初始化你的模拟。您可以在使用 @Before 注释的方法中执行此操作:

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

或者,您可以将运行器从 SpringRunner 更改为:

@RunWith(MockitoJUnitRunner.class)

编辑:

您还必须从您的实现中创建一个 bean:

@Service
public class MyServiceImpl implements MyService

关于java - 单元测试模拟服务实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55115561/

相关文章:

unit-testing - 既然我已经将所有单元测试迁移到 MSpec,我还需要 NUnit 吗?

c - 在 Subversion 中使用 Tessy

java - BaseRepository 查询实体列表 返回对象数组列表

java - 用于两个数据库连接的通用 spring 数据存储库

java - 在 Hibernate 一对一关系中保存外键的问题

c# - resharper 单元测试继承

java - 如何让单元测试每次看到正在执行的java项目中的某个函数时都执行特定的测试用例?

java - 什么是 "Sim blocking"(在 tomcat 文档中看到)?

java - 查找堆栈中出现次数最多的

Java ConcurrentHashMap 原子获取如果存在