I wrote a very simple class in which there is one method which takes Json string and then process for different values. For this there is one helper class also to extract JsonArray and JsonObject based on key. Functionality is working fine but when I am trying to write the unit test the is not as per my expectation. here is code :
public class Test{
@Autowired
private SomeServices someservice;
public Person convertJsonToPerson(String json) {
String content = (String) new JSONObject(json).get("content");
JSONObject talentJson = new JSONObject(content);
getEductionDetail(talentJson);
getContectDetail(talentJson)
}
private JSONArray getEductionDetail(JSONObject jsonObject) {
return someservice.getJsonArray(jsonObject, "educations");
}
private JSONArray getContectDetail(JSONObject jsonObject) {
return someservice.getJsonArray(jsonObject, "educations");
}
}
As it can seen here I have two method to extract json object but in reality class has 20 methods for different purpose.
Here is test case for this.
@Test
public void test() throws IOException {
String json = util.readFile("data.json").trim();
JSONObject jsonOject = new JSONObject(talentJson);
JSONObject edu = new JSONObject();
edu.put("school", "St. Marry");
edu.put("degree", "Master");
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, edu);
when(someservice.getJsonArray(jsonOject, "educations")).thenReturn(jsonArray);
assertNotNull(convertJsonToPerson(json));
}
Following line not working. I think jsonObject here in test and actually code are different that's why id does not matching. Could someone help me on this. How to object based mocking.
when(someservice.getJsonArray(jsonOject, "educations")).thenReturn(jsonArray);
In your code, you define that when the specific instance of jsonObject
is encountered, the mocked someservice
should return the jsonArray
. What you actually want to do, is to return the given jsonArray
for any call to someService.getJsonArray
and the second parameter being "educations". You can do this by using the Mockito matchers like anyObject
or anyString
:
when(someservice.getJsonArray(any(), anyString())).thenReturn(jsonArray);
In case you want to mock the more specific method call with ecudations
or content
you can supply the second parameter with a matcher as well:
when(someservice.getJsonArray(any(), eq("educations"))).thenReturn(jsonArray);
Note: For this to work, someService
needs to be mocked. The specific procedure depends on the frameworks you're using, e. g. in your Test class you do something like
@Mock
private SomeService someService;
@BeforeMethod
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
For more examples see https://dzone.com/articles/use-mockito-mock-autowired