我正在尝试模拟 Service,它负责从存储库获取实体并将它们映射到 Pojo。我收到错误,但我不明白为什么会这样。 有人知道我做错了什么吗?
错误:
class com.example.demo.businessLogic.person.Person cannot be cast to class
com.example.demo.postgres.entity.PersonEntity (com.example.demo.businessLogic.person.Person and
com.example.demo.postgres.entity.PersonEntity are in unnamed module of loader 'app')
java.lang.ClassCastException: class com.example.demo.businessLogic.person.Person cannot be cast to
class com.example.demo.postgres.entity.PersonEntity (com.example.demo.businessLogic.person.Person
and com.example.demo.postgres.entity.PersonEntity are in unnamed module of loader 'app')
personService.getAllPerson() 返回 Pojo:
@Override
public List<Person> getAllPerson() {
return personRepoPostgres.findAll().stream()
.map(personMapper::entityToPerson)
.collect(Collectors.toList());
}
这是测试类:
@ExtendWith(MockitoExtension.class)
@ActiveProfiles("dev")
public class cTest {
@Mock
PersonRepoPostgres personRepoPostgres;
@Mock
PersonMapper personMapper;
@InjectMocks
PersonService personService;
@Test
void test(){
Mockito.when(personService.getAllPerson()).thenReturn(List.of(new Person("Zamor")));
List<Person> personArrayList = personService.getAllPerson();
Assertions.assertEquals(personArrayList.get(0), "Zamor");
}
最佳答案
问题是您试图模拟被测方法,而您应该只模拟被测方法的依赖关系。 Mockito.when
应该用在 PersonRepoPostgress
中的方法上类或 PersonMapper
类,而不是PersonService
.
PersonMapper
没有模拟实现,所以当 personMapper::entityToPerson
被称为默认实现可能正在尝试强制转换 PersonEntity
至Person
.
将您的模拟切换为类似的内容应该会有所帮助:
Mockito.when(personRepoPostgress.findAll()).thenReturn(List.of(new PersonEntity()));
Mockito.when(personMapper.entityToPerson(any(PersonEntity.class))).thenReturn(new Person("Zamor"));
关于java - 模拟服务、注入(inject)存储库和映射器。 Spring 中的集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68550255/