我需要模拟一个JSON对象以对其进行验证。我能够成功进行模拟,但是在调试测试时,实际实现(实际类)中显示了JsonObject异常。这是我的模拟代码,下面是实现。
我需要执行impl的try块中的行。相反,模拟语句最终以JSONException块结尾。
请帮忙吗?
JSONObject pObj = Mockito.mock(JSONObject.class,Mockito.RETURNS_DEEP_STUBS);
pObj.put("currency_code", "USD");
pObj.put("value", "4.56");
JSONArray sArray = Mockito.mock(JSONArray.class,Mockito.RETURNS_DEEP_STUBS);
JSONObject details = Mockito.mock(JSONObject.class,Mockito.RETURNS_DEEP_STUBS);
PowerMockito.when(details.getJSONObject("shipping_amount").getString("value")).thenReturn("4.56");
PowerMockito.when(details.get("shipping")).thenReturn(sArray);
Mockito.doReturn(1).when(shippingArray).length();
Assert.assertEquals(1, shippingArray.length());
PowerMockito.when(sArray.getJSONObject(0).getString("tracking_number")).thenReturn("trackingnumber");
PowerMockito.when(sArray.getJSONObject(0).getString("carrier")).thenReturn("carrier");
````
======Actual impl
if(paResponse.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
String strResponse = paResponse.readEntity(String.class);
JSONObject pObj = new JSONObject(strResponse);
log.debug("Response: "+strResponse);
try {
t.setSamount(pObj.getJSONObject("billing").getJSONObject("shipping_amount").getString("value"));
} catch (JSONException ex) {
log.debug("amount not available");
}
try {
JSONArray sArray = (JSONArray) pObj.get("shipping");
if(sArray.length() > 0) {
try {
t.setTracking_number(sArray.getJSONObject(0).getString("tracking_number"));
t.setShipping_Carr(sArray.getJSONObject(0).getString("carrier"));
} catch (JSONException ex) {
log.debug("tracking number or carrier is not available");
}