如何使用Mockito模拟Mapstruct的toDto方法的page.map(mapper :: toDto)

时间:2019-08-13 12:16:17

标签: java junit java-8 mockito mapstruct

我正在为我的junit方法编写一个service测试用例,该方法具有对jpa repository的外部调用,我想mock
此方法findall(Pageable pageable)返回page映射器正在映射的实体Mapstruct's。 但是,我NPE返回时会得到assert。 我可能缺少某些内容,我不确定如何mock进行此方法调用。

我试图这样写测试用例 测试案例:

public class myTestclass {
@Test
public void testFindAllUser() {
User user1 = new User();
user1.setId(Long.valueOf(1));
User user2 = new User();
user2.setId(Long.valueOf(2));
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(asset2);

Pageable pageable = PageRequest.of(0, 5);
Page<User> userPage = new PageImpl<>(userList, pageable, userList.size());
Page<UserDto> userDtoPage = null;
Mockito.when(userRepositoryMock.findAll(pageable)).thenReturn(userPage);
Mockito.when(userPage.map(userMapperMock::toDto)).thenReturn(userDtoPage);// expecting to mock this object in
// some other way.
assertThat(userService.findAll(pageable)).isEqualTo(userDtoPage); // throws NPE
}
}

我编写测试用例的方法:

public Page<UserDto> findAll(Pageable pageable) 
{

return userRepository.findAll(pageable).map(userMapper::toDto);
}

这是我的映射器类:

@Mapper(componentModel = "spring", uses = { FarmerMapper.class })

public interface UserMapper extends EntityMapper<UserDto, User> {

UserDto toDto(User user);

User toEntity(UserDto userDto);
}

模拟mapper方法toDto以便返回userDto页面的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

由于.map使用UserMapper's toDto方法转换页面的每个元素,因此我模拟了userMapper的多个元素来解决此问题。

因此,我创建了2页,其中一页用于User,另一页用于UserDto。 所以我的测试用例被修改为

@Test
public void testFindAllUser() {
User user1 = new User();
user1.setId(DEFAULT_ID);
User user2 = new User();
user2.setId(2L);
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
Pageable pageable = PageRequest.of(0, 5);
Page<User> userPage = new PageImpl<>(userList, pageable, userList.size());

UserDto userDto1 = new UserDto();
userDto1.setId(Long.valueOf(1));
UserDto userDto2 = new UserDto();
userDto2.setId(Long.valueOf(2));
List<UserDto> userDtoList = new ArrayList<>();
userDtoList.add(userDto1);
userDtoList.add(userDto2);
Page<UserDto> userDtoPage = new PageImpl<>(userDtoList, pageable, userDtoList.size());

Mockito.when(userMapperMock.toDto(user1)).thenReturn(userDto1);
Mockito.when(userMapperMock.toDto(user2)).thenReturn(userDto2); //Mocking the toDto method. 

Mockito.when(userRepositoryMock.findAll(pageable)).thenReturn(userPage);
assertThat(userService.findAll(pageable)).isEqualTo(userDtoPage);
}

现在,如果有更多元素要添加到页面中,我将为所有元素模拟相同的toDto