java - Unit Testing with jUnit and Mockito for External REST API calls -
i building unit tests in spring boot java application service class.
the service class makes external call rest api service return json response. mocking call using mockito. hardcoding json in mockserver response.
is bad practice have hardcoded jsons in unit tests? if json structure changes, test should fail reasoning. there better, best practice this?
example snippet below(the actual code functional, edited snippet brevity idea across, post comment if see errors):
public class userservicetest extends testcase { private static final string mock_url = "baseurl"; private static final string default_user_id = "353"; userservice classundertest; responseentity<customer> mockresponseentity; mockrestserviceserver mockserver; @mock resttemplate mockresttemplate; public void setup() throws exception { super.setup(); classundertest = new userrestservice(); mockresttemplate = new resttemplate(); mockserver = mockrestserviceserver.createserver(mockresttemplate); reflectiontestutils.setfield(classundertest, "resttemplate", mockresttemplate); reflectiontestutils.setfield(classundertest, "usersvcurl", mock_url); } public void testgetuserbyid() throws exception { mockserver.expect(requestto(mock_url + "/users/" + default_user_id)).andexpect(method(httpmethod.get)) .andrespond(withsuccess( "{\n" + " \"usercredentials\": {\n" + " \"password\": \"\",\n" + " \"passwordneedsupdate\": false,\n" + " \"security\": [\n" + " {\n" + " \"answer\": \"\",\n" + " \"question\": \"why did bicycle fall over?\"\n" + " }\n" + " ]\n" + "}" , mediatype.application_json)); customer customer = classundertest.getuserbyid(default_user_id); mockserver.verify(); assertnotnull(customer); assertequals(default_user_id, customer.getid()); } }
i in same boat , reasoning follows: creating dummy json-response mocking object , controlling using mockito.when. need change in when().thenreturn() call when changed inner parsing or expect different results. same json-response calls changed , object representations altered.
therefore guess fine. reading various articles testing rest api's, general concensus creating dummy json-responses practice. best practice (from time time) download real json-response , insert mocked response. way can keep tests up-to-date external party, while tests can run without internet requests.
edit requested:
Comments
Post a Comment