- In |
- On October 29, 2024
Apex Code has built in functionality to call external Web services, such as Amazon Web Services, Facebook, Google, or any publicly available web service. As a result, you will need to have the proper test method code coverage for the related Apex code that makes these callouts. But since the Force.com platform had no control over the external Web service and the impact of making the web service call, test methods can not invoke a 3rd party web service.
This section provides a viable workaround to ensure proper code coverage.
Apex Code has built in functionality to call external Web services, such as Amazon Web Services, Facebook, Google, or any publicly available web service. As a result, you will need to have the proper test method code coverage for the related Apex code that makes these callouts. But since the Force.com platform had no control over the external Web service and the impact of making the web service call, test methods can not invoke a 3rd party web service.
This section provides a viable workaround to ensure proper code coverage.
Later on salesforce provide an implementation for the Webservices Callouts called HttpCalloutMock interface to specify the response sent in the respond method, which the Apex runtime calls to send a response for a callout.
This feature is delivered in Winter 13.
There would be a general mechanism for registering an implementation of a mock interface in a test context:
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
where WebServiceMock is actually the interface provided by Salesforce.
If a mock object is supplied using Test.setMock(), then it will be used to service the request. If there is no mock registered for the appropriate interface, the old behavior of skipping the test will still happen.
An example of its usage:
[codesyntax lang=”java”]
global public SalesforceServicePort
{
global SalesforceServicePort () {
public Integer[] GeneratedInvoices(Integer arg0) {
GeneratedInvoices request_x = new GeneratedInvoices();
GeneratedInvoicesResponse response_x;
request_x.arg0 = arg0;
Map<String, GeneratedInvoicesResponse> response_map_x = new Map<String, GeneratedInvoicesResponse>();
response_map_x.put(‘response_x’, response_x);
WebServiceCallout.invoke (
this,
request_x,
response_map_x,
new String[]
{endpoint_x,
”,
‘http://jbilling/’,
‘GeneratedInvoices’,
‘http://jbilling/’,
‘GeneratedInvoicesResponse’,
‘GeneratedInvoicesResponse’}
);
response_x = response_map_x.get(‘response_x’);
return response_x.return_x;
}
[/codesyntax]
Its test method will be:
[codesyntax lang=”java”]
public static testmethod void jbillingAPIUnitTestMethodCallOut3() {
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
SalesforceServicePort Connection= new SalesforceServicePort();
Connection.GeneratedInvoices(10);
system.assertEquals(Limits.getCallouts(),10);
}
[/codesyntax]