Sub topic 13
A note on WebServiceMock for SOAP
This chapter assumes you have read the earlier chapters on HttpCalloutMock and Test.setMock. You should know why Apex tests cannot make real callouts, and you should be comfortable writing a test class with @IsTest. You don't need to know SOAP in depth. You do need to know that SOAP is an older web service style that exchanges XML messages described by a WSDL file.
Most of this tutorial covers HTTP callouts, where your code builds an HttpRequest and reads an HttpResponse. Some orgs also call SOAP services. Those callouts need a different mock interface, WebServiceMock. The mechanism is the same: register a fake with Test.setMock and let your code call it. The shape of the fake and the way you build its response are different.
Where SOAP callouts come from
You rarely write SOAP callouts by hand. You import a WSDL file in Setup, using Apex Classes > Generate from WSDL. Salesforce then generates Apex classes for you. These classes contain:
- A stub class, which has one method per SOAP operation. You call these methods.
- Request and response wrapper classes, one pair per operation.
- Types for any complex data structures in the WSDL.
When you call a method on the stub, the generated code sends the SOAP envelope and parses the reply. You never touch Http or HttpRequest, so HttpCalloutMock has nothing to intercept.
The examples in this chapter use a calculator service. They assume you generated classes from a WSDL into a class named calculatorServices. That class contains a stub called CalculatorImplPort, an operation doAdd, and a response wrapper doAddResponse. These names come from the WSDL, so the examples run only in an org where you have generated the same classes. Your own WSDL will produce different names, and you should read the generated code to find them.
Why HttpCalloutMock does not work here
Test.setMock takes two arguments: the interface type and an instance of the mock. If you pass HttpCalloutMock.class and then call a WSDL-generated stub, the test fails with an error saying that methods defined as webService or generated callouts are not supported without a mock. The runtime looks for a mock of the matching type, and it does not find one.
The rule is simple:
| Callout style | How the code calls out | Mock interface | Register with |
|---|---|---|---|
| REST or any hand-built HTTP | `new Http().send(req)` | `HttpCalloutMock` | `Test.setMock(HttpCalloutMock.class, mock)` |
| SOAP through WSDL-generated stub | Method on the generated stub class | `WebServiceMock` | `Test.setMock(WebServiceMock.class, mock)` |
If your SOAP service is called through hand-built HttpRequest objects that contain XML, you are really making an HTTP callout. In that case HttpCalloutMock is the right tool.
The WebServiceMock interface
WebServiceMock has one method:
void doInvoke(
Object stub,
Object request,
Map<String, Object> response,
String endpoint,
String soapAction,
String requestName,
String responseNS,
String responseName,
String responseType
)Unlike HttpCalloutMock.respond, this method does not return anything. It receives a map named response, and you put your fake result into that map. The parameters describe the call that is being made:
stubis the generated stub object that made the call.requestis the request wrapper object, for example adoAddinstance holding the arguments.responseis the map you fill in.endpointandsoapActionidentify the service address and the SOAP action header.requestNameis the operation name, such asdoAdd.responseNS,responseName, andresponseTypedescribe the expected response element.
The key you must use in the map is response_x. The generated stub reads that entry to get its result. If you use any other key, the stub finds nothing, and the call fails or returns null.
A first SOAP mock
This mock returns a fixed sum for the calculator's doAdd operation.
@IsTest
public class CalculatorMock 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
) {
calculatorServices.doAddResponse response_x = new calculatorServices.doAddResponse();
response_x.return_x = 3.0;
response.put('response_x', response_x);
}
}The generated doAddResponse class holds the result in a field named return_x. The _x suffix is how the generator avoids clashing with Apex reserved words, since return cannot be a field name. The map key response_x follows the same convention.
The test registers the mock, then calls the stub the same way production code does.
@IsTest
private class CalculatorClientTest {
@IsTest
static void addReturnsMockedSum() {
Test.setMock(WebServiceMock.class, new CalculatorMock());
Test.startTest();
Double result = new calculatorServices.CalculatorImplPort().doAdd(1.0, 2.0);
Test.stopTest();
Assert.areEqual(3.0, result, 'The sum should come from the mock, not a real service');
}
}Notice that the mock ignores the arguments 1.0 and 2.0. The result is always 3.0. The test proves that your code calls the stub and handles the response. It does not prove that the real service adds correctly.
Making the mock respond to the request
A mock that always returns the same value is often not enough. You can read the request parameter by casting it to the generated request class. This lets the mock compute a response from the inputs.
@IsTest
public class EchoingCalculatorMock 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
) {
calculatorServices.doAdd req = (calculatorServices.doAdd) request;
calculatorServices.doAddResponse response_x = new calculatorServices.doAddResponse();
response_x.return_x = req.arg0 + req.arg1;
response.put('response_x', response_x);
}
}The generated request class doAdd has fields named after the WSDL parameters, here arg0 and arg1. Check your own generated code for the real names.
This approach doubles as request verification. If your code passes the wrong arguments, the mock returns the wrong number and your assertion fails.
Several operations in one mock
Each call to Test.setMock(WebServiceMock.class, ...) replaces the earlier mock of that type. If the code under test calls two SOAP operations, a single mock class must serve both. Branch on requestName, which holds the operation name.
@IsTest
public class CalculatorRoutingMock 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
) {
if (requestName == 'doAdd') {
calculatorServices.doAddResponse r = new calculatorServices.doAddResponse();
r.return_x = 3.0;
response.put('response_x', r);
} else {
throw new CalloutException('No mock for operation ' + requestName);
}
}
}Throwing for unknown operations is deliberate. A test that silently receives an empty response hides mistakes. Failing loudly tells you which operation you forgot to mock. This is the same idea as the 404 fallback in the routing mock from the earlier chapter.
Simulating faults
SOAP services report failures as faults, and the generated stub surfaces them as exceptions. To test your error handling, make the mock throw. The exception propagates out of the stub call in your code under test.
@IsTest
public class FailingCalculatorMock 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
) {
throw new CalloutException('Simulated SOAP fault');
}
}@IsTest
private class CalculatorFaultTest {
@IsTest
static void faultSurfacesAsException() {
Test.setMock(WebServiceMock.class, new FailingCalculatorMock());
Test.startTest();
try {
new calculatorServices.CalculatorImplPort().doAdd(1.0, 2.0);
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.isTrue(e.getMessage().contains('Simulated'), 'Message should come from the mock');
}
Test.stopTest();
}
}Assert.fail throws an AssertException, which is not a CalloutException, so it escapes the catch block and fails the test. That is the behavior you want when no exception is thrown.
Gotchas
- Wrong interface. Registering
HttpCalloutMockfor a generated stub fails at the callout. Match the interface to the call style. - Wrong map key. The key must be exactly
response_x. A typo produces a null result that looks like a logic bug in your code. - Wrong response type. The object you put in the map must be the response wrapper class the stub expects. A mismatch causes a type error inside the generated code.
- Regenerated classes. If the WSDL changes and you regenerate, field and class names can change. Your mocks will stop compiling, which is a useful signal that the contract moved.
- Test.startTest and DML. The rule about DML before callouts applies to SOAP too. Do your setup DML before
Test.startTest(), then make the callout inside the test block.
Exercise
A class generated from a WSDL has a stub method getQuote. Your test calls it after Test.setMock(HttpCalloutMock.class, new MyHttpMock()), and the test fails with a message that callouts are not allowed without a mock. What is wrong, and what do you change?
Show answer
Generated SOAP stubs do not use Http.send, so an HttpCalloutMock is never consulted. Implement WebServiceMock instead. In its doInvoke method, create the generated response wrapper object, set its result field, and add it to the response map under the key response_x. Then register it with Test.setMock(WebServiceMock.class, new MyWebServiceMock()) before calling the stub.
Exercise
Your WebServiceMock runs without error, but the stub call in the test returns null. You build the response object correctly. What is the most likely cause?
Show answer
The map key is wrong. The generated stub reads the entry named response_x, so any other key leaves it with nothing to return. Change the call to response.put('response_x', responseObject).