3

I'm trying to figure out how to test a controller method that does both REST and SOAP callouts in the same transaction. Here is the pseudo code:

HelperClass

public static void restCallout(){
   // REST API Callout
}

public static void soapCallout(){
   // SOAP API Callout
}

VFP Controller

public void doPageAction(){
   // Create some data
   insert new Account(Name = 'Test');

   // Do the callouts
   HelperClass.restCallout();
   HelperClass.soapCallout();
   HelperClass.restCallout();
}

Now I can easily test both callout methods in the helper class separately by implementing the HttpCalloutMock and WebServiceMock. I've hit a roadblock when trying to test the doPageAction() method as the Test.setMock will only handle either the HttpCalloutMock.class or the WebServiceMock.class.

How can I handle both mock interfaces in the same method?

4

You can set both types of mocks, which is the purpose of the first parameter.

@isTest static void testPageAction() {
  Test.setMock(WebServiceMock.class, new WSServicesMock());
  Test.setMock(HttpCalloutMock.class, new RestServicesMock());
  // rest of test

Please note that each mock may need to read the input parameters to determine the appropriate output, as you can only set one mock of each type. However, you can definitely respond to both types of callouts that may be in a single function call.

public class WSServicesMock implements WebServiceMock {
    public void doInvoke(
        Object stub,
        Object request,
        Map<String, Object> response,
        String endpoint,
        String soapAction,
        String requestName,
        String responseNS,
        String responseName,
        String responseType) {
            switch(requestName) {
                when 'abc' {
                    // handle first type
                }
                when 'xyz' {
                    // handle second type
                }
                when else {
                    // return an error?
                }
            }
        }
}
  • I had no idea that setMock could be called as many times as needed. I tested it and it seems to be working as expected. Thanks! – Kostadin Stoev Jan 5 at 18:30
  • 2
    @KostadinStoev You're welcome! To be fair, the documentation doesn't explicitly spell this out for us. I actually wrote a unit test to verify the behavior before I answered, just to be sure. – sfdcfox Jan 5 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.