+ Start a Discussion
tim titotim tito 

How to create test class to improve code coverage.

Hi All,

I have developed a trigger for contact on update. as soon as contact update am calling below class from tigger and passing contact id. I am new to write test class for call outs. Can someone help to create test class for below method.
Thanks in adcance. 
public class Helper {
    public static String api_end_point = 'URL';
    
    @future (callout=true)
    public static void afterUpdateContact(String contact_id){
        String post_body = '{"data": {"contactId":"' + contact_id + '"}}';
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(api_end_point);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setBody(post_body);
        HttpResponse response = http.send(request);
        
        if (response.getStatusCode() != 201)
        {
            System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' + response.getStatus());
        }
        else
        {
            System.debug(response.getBody());
        }
        
    }
    
    
}
ayu sharma devayu sharma dev
Hello Tim,

To create the Test class for an Apex class that performs callout you have to create a Mock class which the sample response that you may receive when the actual callout happens.

Create the following test class.
@isTest
private class contactUpdateTest{

    @IsTest
    static void makeCalloutTest(){
        Test.setmock(HttpCalloutMock.class, new mockResponse());
        Test.startTest();
        
        Contact ct = new Contact( FirstName='Test', LastName='Contact' );
        insert ct;

        ct.LastName = 'NewContact'; //Set the field value on which you call the update logic
        update ct;

        Test.stopTest();
        
    }

}

And the following class is the mock class for the test class created above. You can change the Header and Response values accordingly.
global HTTPResponse mockResponse(HTTPRequest req) {
    
    HttpResponse res = new HttpResponse();
    res.setHeader('Content-Type', 'application/json');
    res.setBody('{"example": "test"}');
    res.setStatusCode(200);
    return res;
}

Let me know if any problem occurs. 

Thanks, Ayush Sharma
tim titotim tito
Thank You Ayush. I will check and update you
tim titotim tito
Hi Ayush,

Created as per instructions and still code coverage shwoing 0.

Any other inputs?

Thank you 
ayu sharma devayu sharma dev
Hello Tim,
Can you show me the code from where you are calling this future method?
tim titotim tito
Hi Ayush, Shall we connect via Skype or Zoom? So it is easy to show. Please provide your Skype or any communication. So I will connect
tim titotim tito
Never mind I figurout and fixed. Thank you so much for your help