[英]Mocking Service, Injecting repository & mapper. Integration Tests in Spring
我正在嘗試模擬 Service,它負責從 Repository 獲取實體並將它們映射到 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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.