How to create mock class for multiple Callouts in single class

I am facing a issue with my mock class where I am suppose to create a mock class for a class that makes several callouts in a single method based on criteria’s. Now , when I am trying to create a mock class then it is only acting for the first callout but others callouts are not getting handled.How to work with these classes.

Answer

Here is perhaps the simplest form of a mock that deals with multiple requests.

It is declared as an inner class of the test class so the idea is that it handles all the cases that the outer test class handles. In the respond method you can look at the endpoint of the request or the body of the request and use if/else logic to return the appropriate fake response. (You can also add asserts to verify the details of the request body.)

@IsTest
private class CalloutTest {

    private class Mock implements HttpCalloutMock {
        public HTTPResponse respond(HTTPRequest req) {
            if (req.getEndpoint().endsWith('abc')) {
                HTTPResponse res = new HTTPResponse();
                res.setBody('{}');
                res.setStatusCode(200);
                return res;
            } else if (req.getEndpoint().endsWith('xyz')) {
                ...
            } else {
                System.assert(false, 'unexpected endpoint ' + req.getEndpoint());
                return null;
            }
        }
    }

    @IsTest
    static void abc() {
        Test.setMock(HttpCalloutMock.class, new Mock());
        ...
    }

    @IsTest
    static void xyz() {
        Test.setMock(HttpCalloutMock.class, new Mock());
        ...
    }
}

Attribution
Source : Link , Question Author : R.Rakesh , Answer Author : Community

Leave a Comment