[英]MapStruct not working in service class while running Test cases
I am creating test cases, in one of my service class method I am using mapStruct
to map entity into dto class.我正在创建测试用例,在我的服务类方法之一中,我使用mapStruct
将实体映射到 dto 类。
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.注意 - 在我的实体类中,我有很多字段,但从测试类中我只传递了 3 个参数。
You have annotated your UserMapper with a @Mock annotation, without writing the mockito configuration for this mock.您已经使用 @Mock 注释对您的 UserMapper 进行了注释,而没有为此模拟编写模拟配置。 Then the blank array is expected.然后是空白数组。 Remove the @Mock annotation, or specify what should be returned by the mock.删除 @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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.