I’m starting a new habit of posting regularly on my blog every week. I’ll be kicking it off with tips for creating a generic class or a mocking factory for mocking calls to an external third-party service.
Why do we need to do a mock?
When running unit tests the platform does not allow to do a callout to external dependencies. To test our code base we would need to mock the response as if calling the third party dependency.
By mocking we focus on the code being tested, isolating it from the state and behavior of the external system. The dependencies are simulated and the output state can be controlled.
To start we create a class that implements the HttpCalloutMock. This class enables sending a fake response when doing HTTP callouts. When our code makes a callout, the response will come from our HttpCalloutMock class.
When creating the class we define the constructor and parameters. We can make it generic and serve as a mock factory. Instead of writing several mock classes for every type of response, we only write it once which promotes code reusability best practices. And during unit testing, we define the mock response on the fly.
Here is our sample class which implements the HttpCalloutMock.
And if we have a class that does an HTTP Callout and we want to write a unit test for it. This is how it going to look like.
This is how we would create a unit test.
- Use named credentials when possible when doing HTTP Callouts. Will talk about this more in the future.
- When writing the unit test, the key is to call Test.setMock() which makes sure any callout from your code will return the Mock object.
- Define the mock response on the fly to test different response.
Hope you find this useful. Stay tuned for more coding content and tips. If interested in the source code it is available in GitHub.