-5

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:

enter image description here

1
  • Hi uma and welcome to SFSE! It'll be worth, rather than code dumping, sharing what the error is so people can point you in the right direction as to how to fix it, or for uncovered lines asking specifically how to cover and assert against those kinds of functions etc... :)
    – Dan Jones
    Dec 21 '15 at 9:20
2

You are doing your callout before your mock implementation.

Try reordering the execution to this:

Test.startTest();
    Test.setMock(HttpCalloutMock.class, new Rfleet_MockHttpResponseGenerator());
    Rfleet_Searchaddress.restapi('jso');    
Test.stopTest();

this sets the Mock Response to handle the callout before you actually make the callout in your Rfleet_Searchaddress.restapi method

1
  • Apex Code has built in functionality to call external Web services, such as Amazon Web Services, Facebook, Google, or any publicly available web service. You will also need to have the proper test method code coverage for the related Apex code that makes these
    callouts.
  • But since the Force.com platform has no control over the
    external Web service and the impact of making the web service call, test methods can not invoke a 3rd party web service.
  • With Winter 13, you can now use mock tests with a response that is either hard-coded or reading static resource,

    global class YourHttpCalloutMockImpl implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
    // Create a fake response.
    // Set response values, and
    // return response.
    } }

  • The class that implements the HttpCalloutMock interface can be either global or public.
  • You can annotate this class with @isTest since it will be used only in test context.
  • In this way, you can exclude it from your organization’s code size limit of 3 MB.
  • Now that you have specified the values of the fake response, instruct the Apex runtime to send this fake response by calling Test.setMock
  • in your test method. For the first argument, pass HttpCalloutMock.class, and for the second argument, pass a new instance of your interface implementation of HttpCalloutMock, as follows:

    Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl());

  • After this point, if an HTTP callout is invoked in test context, the callout is not made and you receive the mock response you specified in the respond method implementation.
  • This is a full example that shows how to test an HTTP callout.

    /* Apex class making a callout */

    public class CalloutClass {
    public static HttpResponse getInfoFromExternalService() {
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://api.salesforce.com/endpoint');
    req.setMethod('GET');
    Http h = new Http();
    HttpResponse res = h.send(req);
    return res;
    }
    }

    /* MockResponse class implementing the HttpCalloutMock interface */

    @isTest
    global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
    // Optionally, only send a mock response for a specific endpoint
    // and method.
    System.assertEquals('http://api.salesforce.com/endpoint', 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;
    }
    }

    /* Test Class getting fake response from the class MockHttpResponseGenerator that implements HttpCalloutMock */

    @isTest
    private class CalloutClassTest {
    @isTest static void testCallout() {
    // Set mock callout class
    Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    // Call method to test.
    // This causes a fake response to be sent from the class that implements HttpCalloutMock.
    HttpResponse res = CalloutClass.getInfoFromExternalService();
    // Verify response received contains fake values
    String contentType = res.getHeader('Content-Type');
    System.assert(contentType == 'application/json');
    String actualResponseBody = res.getBody();
    String expectedResponseBody = '{"foo":"bar"}';
    System.assertEquals(actualResponseBody, expectedResponseBody);
    System.assertEquals(200, res.getStatusCode());
    }
    }

1
  • Still am getting the same error
    – uma451
    Dec 21 '15 at 11:01
-1

Remove HttpMockCallout code from test method and check to see if you are in test mode and instantiate the Mock before the actual callout in the method being tested:

req.setMethod('GET');

if (Test.isRunningTest()) { Test.setMock(HttpCalloutMock.class, new Rfleet_MockHttpResponseGenerator()); }

HttpResponse res = h.send(req);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.