【问题标题】:Mocking Service, Injecting repository & mapper. Integration Tests in Spring模拟服务,注入存储库和映射器。 Spring 中的集成测试
【发布时间】:2021-10-03 14:18:28
【问题描述】:

我正在尝试模拟服务,它负责从存储库获取实体并将它们映射到 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");
    }

【问题讨论】:

    标签: java mockito mapstruct


    【解决方案1】:

    问题是你试图模拟被测方法,而你应该只模拟被测方法的依赖关系。 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"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-15
      • 2016-03-13
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多