Mock of RestTemplate in Junit test for mockRestTemplate.post



在春季启动Junit测试中,当它调用when(mockRestTemplate.postForObject(Mockito.any(), Mockito.any(),Mockito.any())).thenReturn(searchDTO)时返回null而不是searchDTO。

@RunWith(SpringJUnit4ClassRunner.class)
public class UserServiceImplTest {
     @InjectMocks
     private UserServiceImpl userService;
     @Mock
     private RestTemplate mockRestTemplate;
     @Mock
     private BeanMapperUtil mockBeanMapperUtil;
     @Mock
     private UserDomain mockUserDomain;
        /**
         * This method will test find by SSN method running as per code or not
         *
         * @throws Exception
         */
        @Test
        public void findBySSNTest() throws Exception {
            UserDTO userDTO = getUserDTO("93ff6e85-fcf4-40c3-9ae8-566791daafa6");
            SearchDTO searchDTO = new SearchDTO();
            searchDTO.setUid("93ff6e85-fcf4-40c3-9ae8-566791daafa6");
            when(mockUserDomain.findByUID("93ff6e85-fcf4-40c3-9ae8-566791daafa6"))
                    .thenReturn(getUser("93ff6e85-fcf4-40c3-9ae8-566791daafa6"));
            when(mockRestTemplate.postForObject(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(searchDTO);
            when(mockBeanMapperUtil.createDtoFromEntity(Mockito.any(), Mockito.any())).thenReturn(userDTO);
            UserDTO mockUserDTO = userService.findBySSN("123-45-6022");
            Assert.assertEquals(mockUserDTO, userDTO);
        }
        /**
         * 
         * This method is used to get User in methods for testing
         * 
         * @return User
         * 
         */
        private User getUser(String id) {
            User mockUser = new User();
            mockUser.setUid(id);
            mockUser.setFirstName("test");
            mockUser.setLastName("test");
            mockUser.setEmail("Test@test.com");
            mockUser.setAddressLine1("Temp Address");
            mockUser.setCity("Temp");
         return mockUser;
        }
        private UserDTO getUserDTO(String id) throws ParseException {
             UserDTO mockUserDTO = new UserDTO();
             mockUserDTO.setUid(id);
             mockUserDTO.setFirstName("test");
             mockUserDTO.setLastName("test");
             mockUserDTO.setEmail("Test@test.com");
             mockUserDTO.setAddressLine1("Temp Address");
             mockUserDTO.setCity("Temp");
       return mockUserDTO;
       }

}

这个测试是与UserServiceImpl类

链接的,这里是UserServiceImpl类的实现,我发现null而不是searchDTO SearchDTO searchDTO = restTemplate.postForObject( REST_END_POINT_STAFF_MASTER_FIND_SSN , requestBody,SearchDTO.class);

UserServiceImpl 方法,其中它是调用和所有其他变量在类中定义,在通过 restTemplate 获取 searchDTO 时发现了 NullpointerException 的错误。

public UserDTO findBySSN(String id) throws UserServiceException {
        try {
            logger.logMethodStart(MessageConstant.METHOD_FIND_BY_USER_WORK_DAY_ID);
            Map<String, String> ssnMap = new HashMap<String, String>();
            ssnMap.put("ssn", id);
            HttpEntity<Map<String, String>> requestBody = new HttpEntity<>(ssnMap);
            SearchDTO searchDTO = restTemplate.postForObject(REST_END_POINT_STAFF_MASTER_FIND_SSN, requestBody,
                    SearchDTO.class);
            System.out.println(searchDTO);
            UserDTO userDTO = null;
            if (searchDTO != null && searchDTO.getUid() != null) {
                logger.logMethodFlow(MessageConstant.METHOD_FIND_BY_USER_SSN, "SearchDTO :", searchDTO);
                userDTO = findByUID(searchDTO.getUid());
                logger.logMethodFlow(MessageConstant.METHOD_FIND_BY_USER_SSN, "Find user by UID", userDTO);
                // If the DTO is null, it means request for new external user, so
                // it'll create a new external user with returned UID and return it.
                if (userDTO != null) {
                    userDTO.setNewExternalUser(false);
                    logger.logMethodEnd(MessageConstant.METHOD_FIND_BY_USER_SSN, userDTO);
                    return userDTO;
                }
                // If the userDTO is not null, it means found userDTO is not new external user,
                // So, set corresponding field to false
                userDTO = new UserDTO();
                userDTO.setUid(searchDTO.getUid());
                userDTO.setNewExternalUser(true);
                logger.logMethodEnd(MessageConstant.METHOD_FIND_BY_USER_SSN, userDTO);
                return userDTO;
            } else {
                String msg = messageSource.getMessage(ErrorMessageEnum.USER_STAFF_MASTER_ERROR.toString(), null,
                        Locale.getDefault());
                logger.logMethodFlow(MessageConstant.METHOD_FIND_BY_USER_SSN, msg);
                throw new UserServiceException(msg, UserServiceExceptionEnum.GET_USER_BY_SSN.toString(),
                        searchDTO.toString(), null);
            }
        } catch (UserServiceException e) {
            throw e;
        } catch (Exception e) {
            String msg = messageSource.getMessage(ErrorMessageEnum.USER_FIND_BY_SSN_ERROR.toString(), null,
                    Locale.getDefault());
            logger.logException(MessageConstant.METHOD_FIND_BY_USER_SSN, e, msg);
            throw new UserServiceException(msg, UserServiceExceptionEnum.GET_USER_BY_SSN.toString(), e.getMessage(),
                    null);
        }
    }

试试这个:

when(mockRestTemplate.postForObject(Mockito.any(String.class), 
                                    Mockito.any(HttpEntity.class),
                                    Mockito.eq(SearchDTO.class)))
                                   .thenReturn(searchDTO);

最新更新