本文介绍了JUnit测试.使用ModelMapper库将实体转换为DTO时的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring Boot Web应用程序,并且对ModelMapper库进行了自定义实现,允许我转换单个对象和对象列表.

I am working on the Spring Boot web app and I have a custom realization of the ModelMapper library that allows me to convert single objects and a list of objects.

@Component
public class ObjectMapperUtils {

@Autowired
private static ModelMapper modelMapper;

static {
    modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}

private ObjectMapperUtils() {
}

public <D, T> D map(final T entity, Class<D> outClass) {
    return modelMapper.map(entity, outClass);
}

public <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
    return entityList.stream().map(entity -> map(entity, outCLass)).collect(Collectors.toList());
}
}

在Service层上,我有一个从DB UserEntity对象返回的方法,并将其转换为UserDTO.

On the Service layer, I have a method returns from DB UserEntity object and convert it to UserDTO.

@Autowired
private UserRepository userRepository;

@Autowired
private ObjectMapperUtils modelMapper;

@Override
public UserDTO getByUserId(String userId) {
    UserEntity userEntity = userRepository.findByUserId(userId)
            .orElseThrow(() -> new NotFoundException("User with userId[" + userId + "] not found"));
    //UserDTO userDTO = new UserDTO();
    //BeanUtils.copyProperties(userEntity, userDTO);
    return modelMapper.map(userEntity, UserDTO.class); // userDTO;
}

当我尝试为此方法创建测试时,会出现问题. UserDTO始终以NULL值返回.

The problem occurs when I try to create a test for this method. UserDTO always returned as NULL value.

class UserServiceImplTest {

@InjectMocks
private UserServiceImpl userService;

@Mock
private UserRepository userRepository;

@Mock
private ObjectMapperUtils modelMapper;

@BeforeEach
void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
void testGetByUserId() {
    UserEntity userEntity = new UserEntity();
    userEntity.setId(1L);
    userEntity.setUsername("zavada");
    userEntity.setUserId("33b4c069-e907-45a9-8d49-2042044c56e0");

    when(userRepository.findByUserId(anyString()))
                 .thenReturn(Optional.of(userEntity));

    UserDTO userDTO = userService.getByUserId("33b4c069-e907-45a9-8d49-2042044c56e0");
    System.out.println(userDTO); <--- NULL

    assertEquals("zavada", userDTO.getUsername());
    assertNotNull(userDTO);

}
}

当我在Service层上使用BeanUtils.copyProperties(obj1,obj2);时进行转换; -测试成功通过.使用ModelMapper我得到NULL.任何想法如何解决此错误或重构代码?预先感谢

When I use on the Service layer converting by BeanUtils.copyProperties(obj1, obj2); - the test is passed successfully. With ModelMapper I get NULL. Any ideas how to solve this error or refactor code? Thanks in advance

推荐答案

要建立在user268396答案的基础上,您需要执行以下操作才能使此功能正常工作:

To build upon user268396 answer you would need the following to get this to work:

@RunWith(MockitoJUnitRunner.class)
    public class StackOverflowTest {

        @InjectMocks
        private StackOverflow userService = new StackOverflow();

        @Mock
        private UserRepository userRepository;

        @Mock
        private ObjectMapperUtils modelMapper;
        private UserDTO userDTO = new UserDTO();
        private UserEntity userEntity = new UserEntity();

        @Before
        public void setUp() {
            when(modelMapper.map(any(), any())).thenReturn(userDTO);

            userDTO.setId(1L);
            userDTO.setUsername("zavada");
            userDTO.setUserId("33b4c069-e907-45a9-8d49-2042044c56e0");
        }

        @Test
        public void testGetByUserId() throws Throwable {
            when(userRepository.findByUserId(anyString())).thenReturn(Optional.of(userEntity));

            UserDTO result = userService.getByUserId("33b4c069-e907-45a9-8d49-2042044c56e0");
            System.out.println(result);

            assertEquals("zavada", result.getUsername());
            assertNotNull(result);

        }
    }

这是一个很容易犯的错误,重要的是要记住,所有@mock对象都不再是真正的实现,并且如果您期望返回任何行为,则需要先对其进行定义.

This is quite an easy mistake to make, it is important to remember that all you @mocked objects are not real implementations anymore and if you expect any behaviour back you would need to define it upfront.

这篇关于JUnit测试.使用ModelMapper库将实体转换为DTO时的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 10:50