-1

Kindly Provide me a feasible solution to write the test class for this below code`

public class ActiveCampaign {
@future (callout=true)
public static void createUser(String Email, String FirstName, String LastName, String contact){
    string key = '1234';
    String authUrl = 'https://navsoft12350.api-us1.com/admin/api.php?api_action=contact_add&api_key='+key;
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint(authUrl);
    request.setMethod('POST');
    request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
    String payload = 'email='+encodingutil.urlencode('Email','utf-8')+'&firstname='+encodingutil.urlencode('FirstName','utf-8')+'&last_name='+encodingutil.urlencode('LastName','utf-8')+'&customer_acct_name='+encodingutil.urlencode('Navsoft, Inc.','UTF-8');
    System.debug(payload);
    HttpResponse response = http.send(request); 
    if (response.getStatusCode() != 200) {
        System.debug('The status code returned was not expected: ' + response.getStatusCode() + ' ' + response.getStatus());
    } else {
        System.debug(response.getBody());
    }
    }
}
0

1 Answer 1

0

You would want to create an HttpCalloutMock implementation for your test class. From the documentation:

Example:

@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://example.com/example/test', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}

Since you're code is also a future method, you'll want to make use of the Test.startTest() and Test.stopTest() methods to execute the future method within your unit test. Trailhead has a great unit that goes through your exact use case: https://trailhead.salesforce.com/en/content/learn/modules/asynchronous_apex/async_apex_future_methods

Not the answer you're looking for? Browse other questions tagged .