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。不确定我是不是对的?
发布于 2021-04-26 23:01:56
首先,您混合了JUnit 4和5版本,因为@ExtendWith注释和MockitoExtension是用于JUnit 5测试的。
删除后,将您的@RunWith注释更改为:
@RunWith(SpringRunner.class)您可以在docs中查看此信息
如果您使用的是JUnit 4,不要忘了在测试中添加@RunWith(SpringRunner.class),否则注释将被忽略。如果您使用的是SpringBootTest5,则不需要添加等效的@ JUnit (SpringExtension.class)作为@SpringBootTest和另一个@…测试注解已经用它进行了注解。
https://stackoverflow.com/questions/67197473
复制相似问题