简体   繁体   中英

Mocking Service, Injecting repository & mapper. Integration Tests in Spring

I'm trying to mock Service, which is responsible for getting Entities from Repository and Mapping them to Pojo. I'm getting an error and I don't understand why it works this way. Does someone know what I'm doing wrong?

Error:

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() returns Pojo:

@Override
public List<Person> getAllPerson() {
    return personRepoPostgres.findAll().stream()
            .map(personMapper::entityToPerson)
            .collect(Collectors.toList());
}

Here is Test class:


@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");
    }

The issue is you are trying to mock the method under test, when you should only mock dependencies of the method under test. Mockito.when should be used on methods in the PersonRepoPostgress class or the PersonMapper class, not PersonService .

There is no mock implementation for PersonMapper , so when personMapper::entityToPerson is called it the default implementation is probably trying to cast PersonEntity to Person .

Switching your mocks to something like this should help:

Mockito.when(personRepoPostgress.findAll()).thenReturn(List.of(new PersonEntity()));
Mockito.when(personMapper.entityToPerson(any(PersonEntity.class))).thenReturn(new Person("Zamor"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM