Mocking

Mocking is the practice of substituting the standard implementation of classes and methods with stub methods that return a fixed value. Other development stacks have rich and robust mocking capabilities built in. Salesforce1, on the other hand, is slowly expanding into the mocking world. In fact, there's only one built-in mock interface for you to stub. Despite the lack of a robust mocking library built into the platform, the capabilities of the existing mock interface make unit testing HTTP callouts a breeze. Additionally, there are other, third-party, mocking libraries that work with the Salesforce1 platform. Libraries, such as FFLib_ApexMocks, found at https://github.com/financialforcedev/fflib-apex-mocks, allow you to stub custom objects and methods so long as you have written your class to implant an interface.

Let's take a deeper look at the HTTPCalloutMock interface. Like most interface implanting classes, there are required methods for you to implement. In the case of HTTPCalloutMock, we must implement the response() method. This method must accept a HTTPRequest object as it's parameter and must return a HTTPResponse object. How we stub that out is up to us. To use our mock object in a test, we simply call: test.setMock(MockObj). After that mock is set, the next callout made will automatically return our stubbed HTTPResponse object. Rather than cluttering up my org with dozens of classes implementing the HTTPCalloutMock interface, I like to code a factory class that constructs the mock for me:

@isTest
public with sharing class CalloutMockFactory implements HttpCalloutMock {
  Protected Integer             code;
  Protected String              status;
  Protected String              bodyAsString;
  Protected Blob                bodyAsBlob;
  Protected Map<String, String> responseHeaders;

  public CalloutMockFactory(Integer code, String status, String body, Map<String, String> responseHeaders) {
    this.code = code;
    this.status = status;
    this.bodyAsString = body;
    this.bodyAsBlob = null;
    this.responseHeaders = responseHeaders;
  }

  public HTTPResponse respond(HTTPRequest req) {
    HttpResponse res = new HttpResponse();
    res.setStatusCode(this.code);
    res.setStatus(this.status);
    res.setBody(this.bodyAsString);
    return res;
  }
}

With this factory in place I can easily test callouts by using the factory to return a response as it's needed. For example:

Test.setMock(HttpCalloutMock.class, new CalloutMockFactory(400, 'Invalid Request',  ps_GuidResp_Tests.json_error, null));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.211