Introduction to Mock Classess in Salesforce
Mock Classes are used in Salesforce to provide a way to create test classes for callouts, with the mock class being able to provide a mock response for the test class. That means if we use a mock class in a test class which is making a callout, we can specify the response to return in the mock class.
Mock Classes for REST Callouts
We can create mock classes by implementing the HttpCalloutMock interface. The syntax for creating a mock class for REST callouts is as follows :
@isTest public class RESTMockClassExample implements HttpCalloutMock { public HTTPResponse respond (HTTPRequest req) { HttpResponse res = new HttpResponse (); res.setStatusCode(200); res.setBody(‘Callout Response Body’); } }
The mock class must implement the HttpCalloutMock interface and it has a respond method which can be used to specify the response to be returned. Once we have created the mock class, we can use it like this in an actual test class :
@isTest private class CalloutTest { @isTest static void myTest() { Test.setMock(HttpCalloutMock.class, new RESTMockClassExample()); HttpResponse res = Callout.makeCallout(); System.assertEquals(200, res.getStatusCode()); } }
We can use the Test.setMock method to set the mock class in our test class. Now, if we make any callouts from the test class (like in the above class, we are making callouts on the Callout.makeCallout() line), the response returned in the test class would be the one that we defined in the mock class.
Mock Classes for SOAP Callouts
We can create mock classes for SOAP callout by implementing the WebServiceMock interface. The syntax for creating a mock class for SOAP callouts is as follows :
@isTest public class SOAPMockExample implements WebServiceMock { public void doInvoke( Object stub, Object request, Mapresponse, String endpoint, String soapAction, String requestName, String responseNS, String responseName, String responseType) { response_x = new SoapResult(); response_x.result = ‘OK’; response.put('response_x', response_x); } }
The mock class must implement the WebServiceMock interface and it has a doInvoke method which can be used to specify the response to be returned. In SOAP test classes, we need to define the response by the wrapper classes specified for the response in your main class. We can use this mock class in a test class like this :
@isTest private class SOAPServiceTest { @isTest static void myTest() { Test.setMock(WebServiceMock.class, new SOAPMockExample()); String result = SOAPService.getResult(); System.assertEquals(‘OK’, result); } }
Just like the REST mock, we can use the Test.setMock method to set the mock class in our test class. Now, if we make any callouts from the test class (like in the above class, we are making callouts on the SOAPService.getResult() line), the response returned in the test class would be the one that we defined in the mock class.