2017-07-11 47 views
0

的錯誤,我已經寫爲代碼工作正常,如Web服務獲得的JUnit

@Service 
public class ConverterService { 

private static final Logger LOGGER = LoggerFactory.getLogger(ConverterService.class); 

private static final String CONVERT_DTO_TO_ENTITY= "convertToEntity called with DTO: "; 

@Autowired 
private ModelMapper modelMapper; 

/** 
* @param userActivityHistoryDto : user activity history object 
* @return - Returns UserActivityLog object 
* @throws JsonProcessingException - Exception raised 
*/ 
public UserActivityLog convertToEntity(UserActivityHistoryDto userActivityHistoryDto) throws JsonProcessingException { 
    LOGGER.debug(CONVERT_DTO_TO_ENTITY + userActivityHistoryDto); 
    final UserActivityLog userActivityLog = modelMapper.map(userActivityHistoryDto, UserActivityLog.class); //getting null in junit 
    ObjectMapper mapper = new ObjectMapper(); 
    ActivityDescriptionDto obj = userActivityHistoryDto.getActivityDescription(); 

    //Object to JSON in String 
    String jsonInString = mapper.writeValueAsString(obj); 
    userActivityLog.setActivityDescription(jsonInString); 
    return userActivityLog; 
} 

}

我傳遞同一個對象,以互聯網服務和測試用例,但得到空JUnit和同一對象完全映射到一個服務web服務調用。測試案例看起來像

@RunWith(MockitoJUnitRunner.class) 
public class ConverterServiceTest { 

@InjectMocks 
private ConverterService converterService; 

@Mock 
private ModelMapper modelMapper; 

@Test 
public void testConvertEntity() throws JsonParseException, JsonMappingException, IOException{ 
    ObjectMapper mapper = new ObjectMapper(); 
    UserActivityHistoryDto userActivityHistoryDto = mapper.readValue(Resources.getResource("CreateUserHistoryLog.json"), UserActivityHistoryDto.class); 

    UserActivityLog userActivityLog = converterService.convertToEntity(userActivityHistoryDto); 
    Assert.assertEquals("UPD_COMPY",userActivityLog.getActivityTypeCode().getActivityTypeCode()); 
    Assert.assertEquals("CID",userActivityLog.getKeyId()); 
    Assert.assertEquals("202020",userActivityLog.getKeyValueText()); 
    Assert.assertEquals("I",userActivityLog.getAudienceTypeCode()); 
    Assert.assertNotNull(userActivityLog.getActivityDescription()); 
} 
} 

請幫我知道最近出了什麼問題。

+0

我們展示的堆棧跟蹤。你已經將ModelMapper聲明爲模擬。你有沒有定義'modelMapper.map(...)'應該返回什麼? – pvpkiran

回答

1

您正在使用模擬對象,因此您需要在調用方法時存根方法以說出想要獲取的內容。默認情況下,未打開的方法通常返回null。

當你正在呼籲modelMapper的方法映射,在您的測試,你需要這樣的東西:

when(modelMapper.map(anyObject(), eq(UserActivityHistoryDto.class))).thenReturn(/**What you want to return**/ new userActivityHistoryDto()); 

,看一下文檔:Mockito