I'm trying to unit test the behavior of some code which performs callouts and its logic is dependent on the HTTP status code of the response - 200 vs 401.
The pattern being exercised is familiar:
- Make callout
- Response is (unauthorized) HTTP 401
- Logic checks Status value on the response
if (status == 200) { /* yay! */ }if (status == 401) { /* make request for auth /* }- retry original callout with newly acquired authorization
- yay!
I am attempting to test the code's "try, auth, retry" behavior using the MultiStaticResourceCalloutMock but it appears that only a single status code can be set for all requests that the mock provider can respond to using the .setStatusCode(int) method. Is this accurate?
Is there a mechanism for using a single MultiStaticResourceCalloutMock and having it respond with different status codes per URL in the test context?
Is the only solution here to use a Dispatcher such as what Andrew Fawcett documents here in this answer? https://salesforce.stackexchange.com/a/19263/660
Is there another method/mechanism that allows for different status codes to be returned by the mock provider on the HTTPResponse?
Some generic testing code from Salesforce showing the one-time usage pattern of the .setStatusCode(200) method and the multimock class.
@isTest
private class CalloutMultiStaticClassTest {
@isTest static void testCalloutWithMultipleStaticResources() {
// Use MultiStaticResourceCalloutMock to
// specify fake response for a certain endpoint and
// include response body in a static resource.
MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock();
multimock.setStaticResource(
'http://api.salesforce.com/foo/bar', 'mockResponse');
multimock.setStaticResource(
'http://api.salesforce.com/foo/sfdc', 'mockResponse2');
multimock.setStatusCode(200);
multimock.setHeader('Content-Type', 'application/json');
// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, multimock);
// Call the method for the first endpoint
HTTPResponse res = CalloutMultiStaticClass.getInfoFromExternalService(
'http://api.salesforce.com/foo/bar');
// Verify response received
System.assertEquals('{"hah":"fooled you"}', res.getBody());
// Call the method for the second endpoint
HTTPResponse res2 = CalloutMultiStaticClass.getInfoFromExternalService(
'http://api.salesforce.com/foo/sfdc');
// Verify response received
System.assertEquals('{"hah":"fooled you twice"}', res2.getBody());
}
}