I am trying to mock MAPPER.readValue() but cant get the expected output.
private static final ObjectMapper MAPPER = new ObjectMapper();
String res = EntityUtils.toString(response.getEntity());
PartyDetailInfo partyInfo = MAPPER.readValue(res, PartyDetailInfo.class);
if (partyInfo.getXpartyInfo() == null || partyInfo.getXpartyInfo().getXpartyInfoItem() == null
|| partyInfo.getXpartyInfo().getXpartyInfoItem().get(0).getOrigSystemRefs() == null
|| partyInfo.getXpartyInfo().getXpartyInfoItem().get(0).getOrigSystemRefs().getOrigSystemRefsItems()
.isEmpty()) {
BusinessException exception = new BusinessException(Constants.ERROR_PARTY_ID_NOT_EXIST
.replace(Constants.TEMP_ZERO_REPLACE_STRING, partyDetailRequest.getPartyId()));
exception.setErrorCode(Integer.toString(HttpStatus.SC_NOT_FOUND));
throw exception;
}
I tried mocking it but i ge partyInfo = null;
Mockito.when(Mapper.readValue(Mockito.anyString(),Mockito.eq(PartyDetailInfo.class))).thenReturn(getPartyInfoDummy());
Here's the getPartyInfoDummy():
private PartyDetailInfo getPartyInfoDummy(){
List<XpartyInfoItem> xpartyInfoItems = new ArrayList<XpartyInfoItem>();
XpartyInfoItem infoItem = new XpartyInfoItem();
OrigSystemRefs origSystemRefs = new OrigSystemRefs();
OrigSystemRefsItem origSystemRefsItem = new OrigSystemRefsItem();
List<OrigSystemRefsItem> origSystemRefsItems = new ArrayList<OrigSystemRefsItem>();
origSystemRefsItem.setOrigSystem("PSFT");
origSystemRefsItem.setOrigSystemReference("PS-47439934");
PrimaryMlsSet primaryMlsSet = new PrimaryMlsSet();
primaryMlsSet.setNil("true");
origSystemRefsItem.setPrimaryMlsSet(primaryMlsSet );
origSystemRefsItems.add(origSystemRefsItem);
origSystemRefs.setOrigSystemRefsItems(origSystemRefsItems );
infoItem.setOrigSystemRefs(origSystemRefs);
xpartyInfoItems.add(infoItem);
PartyDetailInfo partyInfo = new PartyDetailInfo();
XpartyInfo xpartyInfo = new XpartyInfo();
xpartyInfo.setxReturnStatus(null);
xpartyInfo.setxErrMsgs(null);
xpartyInfo.setXpartyInfoItem(xpartyInfoItems);
partyInfo.setXpartyInfo(xpartyInfo);
return partyInfo;
}
I dont understand whats going wrong here? Need help.
当您说Mockito.when(Mapper.readValue
请确保映射器是一个Mockito.when(Mapper.readValue
对象,并且Mockito.when(Mapper.readValue
映射器设置为您尝试测试的实例。
Firstly, your Mapper is a locally created object and secondly it is static and final. You cannot mock such objects using mockito. Use Powermock.
在这种问题中,您也可以尝试使用Mockito.doReturn(...).when(...)
,当我遇到类似的问题时,它会有所帮助。
This worked for me on a similar case:
doThrow(IOException.class).when(objectMapper).readValue(any(A_Random_Class.class), any(Class.class));
This is the method I tried to mock:
public <T> T readValue(File src, JavaType valueType) throws IOException, JsonParseException, JsonMappingException {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.