Monday, December 3, 2018

Mock HTTP callouts in a Managed Package

In this blog, I will show you how to mock callout response which is in a managed package.

I found out that many developers are using Test.IsRunningTest() in their Apex classes to avoid writing Mock responses for http callouts and if the callout comes from a Managed Package, they are stuck with this message "Methods defined as TestMethod do not support Web service callouts".

As per Salesforce Documentation, "To mock a callout if the code that performs the callout is in a managed package, call Test.setMock from a test method in the same package with the same namespace."

So to be able to mock callout which is performed in a managed package, the line doing "Test.setMock" should be called from the managed package itself.

So what we did in the SharinPix (ISV) managed package, we added a global class which take a HttpCalloutMock class as parameter and execute the Test.setMock from within the package.

global class HttpCalloutSimulator {
    global static void setMock(HttpCalloutMock mock) {
        Test.setMock(HttpCalloutMock.class, mock);

By adding the above class in your package and making it global so that it ca be called outside the managed package make it easy to mock code which are doing callout in your package without getting error messages.

You will just need to call it as below:


Example on how to use it:

sharinpix.HttpCalloutSimulator.setMock(HttpCalloutMock mock);  
//where the variable mock is the instance of your HttpCalloutMock class


1 comment:

  1. The ball will start to decelerate as it goes past a number of|numerous|a selection of} deflectors, it'll then drop on the wheel and find yourself in any one of many pockets, that are either purple or black and numbered. Play begins after the dealer has cleared off all losing bets and paid all winners from the previous spin. Players dafabet are given time to put down bets by putting chips on the format before the dealer begins the spin. After the spin has begun, players may keep betting till the ball is about to drop from the monitor on the high of the wheel down towards the numbered slots. The bottom line is that American roulette players buck a house edge of 5.26 percent on all bets however one, which carries a 7.89 percent house edge.