[SalesForce] cover httpRespone and if condition in test class

while calling method

@isTest
  public class call_Test{
     static testMethod void unitTest(){
      uptodel.qTis();
     }
  }

its given error that Methods defined as TestMethod do not support Web service callouts

public class uptodel {
     public static final String ts_url = 'https://example.com/study';
     public static void qTis() {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(ts_url);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
            if (response.getStatusCode() == 200) {
                Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                List<Object> contacts = (List<Object>) results.get('contacts');
                for (Object contact: contacts) {
                    System.debug(contact);
                }
            }

    }
}

Best Answer

Since your test calls a method that executes a callout you need to mock the response during test methods.

The easiest way to do this is in sfdcfox's post here:

Help on Invokable Apex Test class and @Future callout Apex test Class

@isTest class MakeCalloutTest {
    // Simple echo callout class
    // Returns whatever response we tell it to when asked
    class EchoHttpMock implements HttpCalloutMock {
        HttpResponse res;
        EchoMock(HttpResponse r) {
            res = r;
        }
        // This is the HttpCalloutMock interface method
        public HttpResponse respond(HttpRequest req) {
            return res;
        }
    }

    @isTest static void test() {
        // Avoid using live data
        List<Lead> leads = new List<Lead>{ new Lead(LastName='Test',Company='test') };
        insert leads;
        // We tell it what to simulate
        HttpResponse res = new HttpResponse();
        res.setBody('<?xml version="1.0" encoding="utf-8"?><root U_Id="12345"></root>');
        res.setStatusCode(200);
        // This allows the callout to succeed
        Test.setMock(HttpCalloutMock.class, new EchoHttpMock(res));
        // Start the test
        Test.startTest();
        // Enqueue the future call
        MakeCallout.invokeleadcallout(leads);
        // Trigger future method
        Test.stopTest();
        // Verify logic
        leads = [select id__c from lead];
        System.assertEquals('12345', leads[0].Id__c);
    }
}

He was even kind enough to put an example test method in there

Related Topic