【问题标题】:Unable to mock mongoRepository instance无法模拟 mongoRepository 实例
【发布时间】:2021-07-15 17:52:00
【问题描述】:
import static org.mockito.Mockito.when;

import java.util.ArrayList;

import org.junit.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.poc.kafka.mongo.entity.Employee;
import com.poc.kafka.mongo.repository.EmployeeMongoRepository;
import com.poc.kafka.mongo.service.EmployeeService;
import com.poc.kafka.mongo.service.EmployeeServiceImpl;

@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class EmployeeServiceMockTests {
    @InjectMocks
    EmployeeService employeeService=new EmployeeServiceImpl();
    @Mock
    EmployeeMongoRepository employeeMongoRepository;
    
    @Test
    public void testFindAll() {
        when(employeeMongoRepository.findAll()).thenReturn(new ArrayList<Employee>());
        employeeService.findAll();
    }
}

我正在尝试模拟从 MongoRepository 类扩展到服务但无法模拟的employeeMongoRepository 实例。模拟对象越来越为空。我正在使用 spring-boot-test、mockito 和 junit-vintage。不知道我说的对不对?

【问题讨论】:

    标签: mongodb mockito spring-boot-test junit-jupiter junit-vintage


    【解决方案1】:

    首先,您要混合使用 JUnit 4 和 5 版本,因为 @ExtendWith 注释和 MockitoExtension 用于 JUnit 5 测试。

    删除后,将您的 @RunWith 注释更改为:

    @RunWith(SpringRunner.class)
    

    您可以在docs查看此信息:

    如果您使用的是 JUnit 4,请不要忘记将 @RunWith(SpringRunner.class) 也添加到您的测试中,否则注释将被忽略。如果您使用的是 JUnit 5,则无需将等效的 @ExtendWith(SpringExtension.class) 添加为 @SpringBootTest 并且其他 @…Test 注释已使用它进行注释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      相关资源
      最近更新 更多