Recently i have written a test class for Webservice.i got 79% .But the test class failed. And the error is "Methods defined as Test Method do not support Web service callouts ". how to resolve this error and improve code coverage?
My apex class :
global class Rfleet_Searchaddress {
public String StNumber {get;set;}
public String Bcity {get;set;}
public String BPostalcode {get;set;}
public String BCountry {get;set;}
public String Snumber {get;set;}
public String street {get;set;}
public Boolean refreshPage {get;set;}
string Id;
list < Account > updateAdd = new list < Account > ();
//This method is constructor
public Rfleet_Searchaddress(ApexPages.StandardController controller) {
id = ApexPages.currentPage().getParameters().get('id');
refreshPage = false;
}
//This method is autosave the addresses
public void autosave() {
for (Account updatelist: [SELECT id, Rfleet_Main_Address_Number__c, Rfleet_Main_address_Street__c, BillingAddress, BillingCity, BillingCountry, BillingPostalCode, BillingState, BillingStreet FROM Account where id = : id]) {
updatelist.BillingStreet = Snumber + ' ' + street; //StNumber;
updatelist.BillingCity = Bcity;
updatelist.BillingPostalCode = BPostalcode;
updatelist.BillingState = '';
updatelist.BillingCountry = BCountry;
updatelist.Rfleet_Main_Address_Number__c = Snumber;
updatelist.Rfleet_Main_address_Street__c = street;
updateAdd.add(updatelist);
}
try{
update updateAdd;
}catch(DmlException e) {
system.debug('update--->' + updateAdd);
}
refreshPage = true;
}
//This method is remote action
@RemoteAction
global static list < String > restapi(string accName) {
string jsonStr;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setHeader('Accept', 'application/JSON');
req.setEndpoint('http://api-adresse.data.gouv.fr/search/?q=' + EncodingUtil.urlEncode(accName, 'UTF-8')); //+'&'+'limit'+'='+'10');//
req.setMethod('GET');
HttpResponse res = h.send(req);
system.debug('res1===>' + res.getBody());
List < String > calOut1 = new List < String > ();
JSON2Apex parsed = JSON2Apex.parse(res.getBody());
for (JSON2Apex.Features f: parsed.Features) {
JSON2Apex.Properties p = f.Properties;
calOut1.add(p.label + ' ' + 'FRANCE');
}
return calOut1;
}
}
JSON2apex:
public class JSON2Apex {
public String query;
public String version;
public String licence;
public List<Features> features;
public String type;
public String attribution;
public class Geometry {
public List<Double> coordinates;
public String type;
}
public class Features {
public Geometry geometry;
public String type;
public Properties properties;
}
public class Properties {
public String city;
public String label;
public String id;
public String postcode;
public String name;
public String citycode;
public String context;
public Double score;
public String type;
}
public static JSON2Apex parse(String json) {
return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}
static testMethod void testParse() {
String json = '{\"query\": \"8\", \"version\": \"draft\", \"licence\": \"ODbL 1.0\", \"features\": [{\"geometry\": {\"coordinates\": [5.600741, 43.28252], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Aubagne\", \"label\": \"Route Nationale 8 13400 Aubagne\", \"id\": \"13005_XXXX_b0c6c8\", \"postcode\": \"13400\", \"name\": \"Route Nationale 8\", \"citycode\": \"13005\", \"context\": \"13, Bouches-du-Rh\\u00f4ne, Provence-Alpes-C\\u00f4te d\'Azur\", \"score\": 0.6540636363636363, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [5.864773, 43.132774], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Ollioules\", \"label\": \"Route Nationale 8 83190 Ollioules\", \"id\": \"83090_XXXX_a33650\", \"postcode\": \"83190\", \"name\": \"Route Nationale 8\", \"citycode\": \"83090\", \"context\": \"83, Var, Provence-Alpes-C\\u00f4te d\'Azur\", \"score\": 0.6526818181818181, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [45.136426, -12.845884], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Ouangani\", \"label\": \"Route D\\u00e9partementale 8 97670 Ouangani\", \"id\": \"97614_XXXX_704587\", \"postcode\": \"97670\", \"name\": \"Route D\\u00e9partementale 8\", \"citycode\": \"97614\", \"context\": \"976, Mayotte\", \"score\": 0.6507545454545454, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [5.86687, 43.132284], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"Ollioules\", \"label\": \"Route Nationale 8 83190 Ollioules\", \"id\": \"83090_XXXX_9346fc\", \"postcode\": \"83190\", \"name\": \"Route Nationale 8\", \"citycode\": \"83090\", \"context\": \"83, Var, Provence-Alpes-C\\u00f4te d\'Azur\", \"score\": 0.6481181818181817, \"type\": \"street\"}}, {\"geometry\": {\"coordinates\": [3.242916, 43.379135], \"type\": \"Point\"}, \"type\": \"Feature\", \"properties\": {\"city\": \"B\\u00e9ziers\", \"label\": \"Chemin Rural 8 34500 B\\u00e9ziers\", \"id\": \"34032_XXXX_ddb1db\", \"postcode\": \"34500\", \"name\": \"Chemin Rural 8\", \"citycode\": \"34032\", \"context\": \"34, H\\u00e9rault, Languedoc-Roussillon\", \"score\": 0.6467545454545454, \"type\": \"locality\"}}], \"type\": \"FeatureCollection\", \"attribution\": \"BAN\"}';
JSON2Apex obj = parse(json);
System.assert(obj != null);
}
}
Mockup test class:
@isTest
global class Rfleet_MockHttpResponseGenerator_Test implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
// Optionally, only send a mock response for a specific endpoint
// and method.
System.assertEquals('http://api-adresse.data.gouv.fr/search/?q='+'france', req.getEndpoint());
System.assertEquals('GET', req.getMethod());
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"foo":"bar"}');
res.setStatusCode(200);
return res;
}
}
My test class :
@isTest
public class Rfleet_Searchaddress_test {
@isTest static void Testsearchaddress() {
Account testAccount = new Account(Name='chinna',Montant__c=5);
insert testAccount;
testAccount.BillingStreet='chengalpattu';
update testAccount;
Account myTestTrainee = [SELECT id From Account LIMIT 1];
PageReference myVfPage = Page.RFLEET_Searchaddress;
system.test.setCurrentPage(myVfPage);
ApexPages.currentPage().getParameters().put('id', myTestTrainee.id);//Pass Id to page
ApexPAges.StandardController sc = new ApexPages.StandardController(myTestTrainee);
Rfleet_Searchaddress apextestclass=new Rfleet_Searchaddress(sc);
apextestclass.autosave();
String param ='Base Product';
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = 'http://api-adresse.data.gouv.fr/search/?q=';
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = res;
Rfleet_Searchaddress.restapi('jso');
Test.startTest();
Test.setMock(HttpCalloutMock.class, new Rfleet_MockHttpResponseGenerator());
Test.stopTest();
}
}
The uncovered lines are: