I am creating test cases, in one of my service class method I am using mapStruct
to map entity into dto class.
This is my mapper class
@Mapper(componentModel = "spring")
public interface UserMapper {
List<UserDto> toUserDto(List<UserEntity> users);
}
below is how I am injecting in my service class
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService{
private final UserMapper userMapper;
This is how I am using it
List<UserDto> userDto = userMapper.toUserDto(lst);
this is how I am doing it in my Test class
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTest {
@Mock
private UserRepository userRepo;
@Mock
private UserMapper userMapper;
@InjectMocks
private UserServiceImpl userServiceImpl;
@Test
public void contextLoads() {
then(controller).isNotNull();
then(userServiceImpl).isNotNull();
}
@Test
public void getAllUser() {
List<UserEntity> lst = new ArrayList<UserEntity>();
UserEntity userOne = new UserEntity();
userOne.setEmpFullname("Test Test1");
userOne.setUserId("marina");
userOne.setFlag("Y");
UserEntity usertwo = new UserEntity();
usertwo.setEmpFullname("Test Test2");
usertwo.setUserId("test");
usertwo.setFlag("Y");
lst.add(userOne);
lst.add(usertwo);
when(userRepo.findByStatus("W")).thenReturn(lst);
try {
List<UserDto> pendingUsersList = userServiceImpl.getPendingUser();
assertEquals(2, pendingUsersList.size());
} catch (GeneralException e) {
e.printStackTrace();
}
}
}
when I am running my test cases I am able to see these 2 records in entity class but when this line executes
List<UserDto> userDto = userMapper.toUserDto(lst);
it gives me blank array.
Note - In my entity Class I have many fields but from test class I am passing only 3 parameters.
CodePudding user response:
You have annotated your UserMapper with a @Mock annotation, without writing the mockito configuration for this mock. Then the blank array is expected.
Remove the @Mock annotation, or specify what should be returned by the mock.
For example :
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = Application.class)
public class ApplicationTest {
@Mock
private UserRepository userRepo;
@Spy
private UserMapper userMapper = Mappers.getMapper(UserMapper.class);
@InjectMocks
private UserServiceImpl userServiceImpl;