java - Junit test case for a restful client using mockito -
i have no idea before how write test cases, when saw online tutorials understand how write simple method success , failure scenario. have method http calls restful api , returns json response. have 6 parameters include in url , json response back. now, understanding far success scenario here should hard code input parameters , test if getting json , failure not getting json response back. correct or have else?
i mean have code like
public list getstorelocations(storedata storedata) { list storelist = null; try { httpclient httpclient = httpclientbuilder.create().build(); stringbuilder urlstrngbuildr = new stringbuilder( https://<hostname>/xyz/abc); utility.addparametertourl(urlstrngbuildr, utility.app_name, constants.app_value); utility.addparametertourl(urlstrngbuildr, constants.version_param_name, constants.version_param_value); if (storedata.getcity() != null && storedata.getstate() != null) { stringbuilder addressparamvalue = new stringbuilder( storedata.getcity()); addressparamvalue.append(constants.comma); addressparamvalue.append(storedata.getstate()); utility.addparametertourl(urlstrngbuildr, constants.address_param_name, addressparamvalue.tostring()); } else if (storedata.getzip() != null) { utility.addparametertourl(urlstrngbuildr, constants.zip_param_name, storedata.getzip()); } utility.addparametertourl(urlstrngbuildr, constants.product_param_name, storedata.getproduct()); utility.addparametertourl(urlstrngbuildr, constants.country_param_name, storedata.getcountry()); utility.addparametertourl(urlstrngbuildr, constants.distance_param_name, storedata.getdistance()); utility.addparametertourl(urlstrngbuildr, constants.size_param_name, storedata.getsize()); httpget getrequest = new httpget(new java.net.uri( urlstrngbuildr.tostring())); getrequest.addheader(basicscheme.authenticate( new usernamepasswordcredentials(username,password), constants.encoding_type, false)); jsonresponsehandler responsehandler = new jsonresponsehandler(); string json = httpclient.execute(getrequest, responsehandler) .tostring(); gson gson = new gson(); storeresponse response = gson.fromjson(json, storeresponse.class); storedetails[] strdetails = response.getresult(); storedetailslist = arrays.aslist(strdetails); } catch (exception exeption) { exeption.printstacktrace(); } return storelist; }
maybe should take @ rest-assured, rest api testing framework.
the nice thing is, easier read, supports json , xml , allows test things http-codes or specific values response.
get("/lotto") .then() .assertthat().body("lotto.lottoid", equalto(5));
you add parameters param
method:
given() .param("key1", "value1") .param("key2", "value2") when(). aso...
if need authentication, in code, can use following:
given() .auth() .basic(username,password) .when() .get("/secured") .then() .statuscode(200);`
hope helps testing.
Comments
Post a Comment