首页 技术 正文
技术 2022年11月15日
0 收藏 342 点赞 3,726 浏览 5766 个字

此篇可以参考:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm

https://developer.salesforce.com/trailhead/force_com_dev_intermediate/apex_integration_services/apex_integration_rest_callouts

在项目中我们经常会用到通过http方式和其他系统交互,在salesforce 零基础学习(三十三)通过REST方式访问外部数据以及JAVA通过rest方式访问salesforce这篇讲过http callout方式使用,

简单callout demo如下:

 public class CalloutClass {     //default out of time
private static final Integer OUT_OF_TIME = 10000;
//default method : get
private static final String DEFAULT_METHOD_GET = 'GET'; private static final Integer STATUS_CODE_OK = 200; public static String getDataViaHttp(String endPoint,String param) {
return getDataViaHttp(endPoint,DEFAULT_METHOD_GET,param);
} public static String getDataViaHttp(String endPoint,String method,String param) {
return getDataViaHttp(endPoint,method,param,OUT_OF_TIME);
} public static String getDataViaHttp(String endPoint,String method,String param,Integer outOfTime) {
HttpRequest req = new HttpRequest();
Http h = new Http();
req.setMethod(method);
req.setHeader('Content-Type', 'application/json');
if(param != null) {
req.setBody(param);
}
req.setEndpoint(endPoint);
req.setTimeout(outOfTime);
HttpResponse res = h.send(req);
if(res.getStatusCode() == STATUS_CODE_OK) {
return res.getBody();
} else {
throw new CallOutException('访问失败');
}
} class CallOutException extends Exception { }
}

有的时候我们需要在batch中调用http接口和其他系统交互进行字段更新等操作,如果在batch中需要用到http callout,需要实现Database.AllowsCallouts接口,demo如下:

 public with sharing class CalloutBatchClass implements Database.Batchable<sObject>,Database.AllowsCallouts{
public Database.QueryLocator start(Database.BatchableContext BC) {
String fetchSQL = 'fetch sql';
return Database.getQueryLocator(fetchSQL);
} public void execute(Database.BatchableContext BC, List<sObject> objList) {
String endPoint = 'site end point';
String responseData = CalloutClass.getDataViaHttp(endPoint,null);
for(sObject obj : objList) {
//TODO
}
} public void finish(Database.BatchableContext BC) { }
}

项目中test class是必需的,而且正常要求test class覆盖率超过75%。test class中不允许http callout,我们可以通过实现HttpCalloutMock接口模拟http请求的返回值。通过重写respond方法实现

不同的http请求所返回的不同的response状态和body内容。

 @isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
global String method; global String METHOD1_BODY = '{"foo":"bar"}'; global String METHOD2_BODY = '{"foo":"bar2"}'; global MockHttpResponseGenerator() {} global MockHttpResponseGenerator(String requestMethod) {
method = requestMethod;
} // Implement this interface method
global HTTPResponse respond(HTTPRequest req) {
// Create a fake response
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
String body;
if(method == 'method1') {
body = METHOD1_BODY;
} else if(method == 'method2') {
body = METHOD2_BODY;
} else if(method == 'methodError') {
res.setStatusCode(500);
}
res.setBody('{"foo":"bar"}');
if(res.getStatusCode() != null) {
res.setStatusCode(200);
}
return res;
}
}

简单的测试CalloutClass的测试类如下:

@isTest
private class CalloutClassTest {
@isTest static void testSuccessCallout() {
Test.startTest();
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator('method1'));
String endPoint = 'http://api.salesforce.com/foo/bar';
String result = CalloutClass.getDataViaHttp(endPoint,'test param');
String expectedValue = '{"foo":"bar"}';
System.assertEquals(result, expectedValue);
Test.stopTest();
}
}

这只是我们碰到的所谓最理想的情况,有的时候我们往往会碰到这样一种情况:一个方法里面需要调用到多个http callout。比如需要先进行http callout,将返回值作为参数或者oauth setting内容然后继续进行callout,这种情况下使用上述的方式便比较难实现,毕竟上述mock形式仅作为一个http callout的response。这个时候我们要变通一下,看看前面的调用是否是必要的–前后几次调用是否有并列关系,还是仅将前几次调用作为相关参数为最后一次做准备,此种情况下,可以在类中设置相关的静态变量来跳过相关的调用;如果前后几次调用属于并列关系,需要对每一次的response的内容进行相关处理,这种情况下的test class便需要使用multi mock形式。

一.非并列关系:此种方式可以使用变量方式跳过相关的调用

 public with sharing class CalloutClassUseVariable {
public static Boolean skipForTest{get;set;}
public STring getResult(String endPoint1,String endPoint2) {
String result1 = '';
if(skipForTest == null ||skipForTest == false) {
result1 = CalloutClass.getDataViaHttp(endPoint1,'');
}
String result2 = CalloutClass.getDataViaHttp(endPoint2,result1);
return result2;
}
}

相关test class处理

 @isTest
private class CalloutClassUseVariableTest {
static testMethod void testMethod1() {
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator('method1'));
String endPoint = 'http://api.salesforce.com/foo/bar';
CalloutClassUseVariable.skipForTest = true;
String result = CalloutClassUseVariable.getResult('', endPoint);
String expectedValue = '{"foo":"bar"}';
System.assertEquals(result, expectedValue);
Test.stopTest();
}
}

二.并列关系:此种方式需要使用MultiStaticResourceCalloutMock方式。

salesforce提供MultiStaticResourceCalloutMock接口实现多个callout的test class模拟response请求,可以将response的body值放在txt文档中上传至static resources中,然后test class引用相关静态资源实现模拟多个response返回。

 public with sharing class CalloutController {
public String result{get;set;}
public void getResult(String endPoint1,String endPoint2) {
String result1 = CalloutClass.getDataViaHttp(endPoint1,'');
String result2 = CalloutClass.getDataViaHttp(endPoint2,'');
result = result1 + result2;
}
}

相关test class处理:

1.将需要的相关response body值上传至static resource中;

2.test class编写

 @isTest
private class CalloutClassUseMultiStaticResourceTest {
static testMethod void testMethod1() {
MultiStaticResourceCalloutMock mock = new MultiStaticResourceCalloutMock();
String endPoint1 = 'http://api.salesforce.com/foo/bar';
String endPoint2 = 'http://api.salesforce.com/foo/sfdc';
mock.setStaticResource(endPoint1, 'Callout_Method1_TestResponse');
mock.setStaticResource(endPoint2, 'Callout_Method2_TestResponse');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
CalloutController controller = new CalloutController();
controller.getResult(endPoint1,endPoint2);
String expectedResult = '{"foo":"bar"}{"foo":"bar2"}';
system.assertEquals(expectedResult,controller.result);
Test.stopTest();
}
}

总结:callout test class编写可以主要看方法中对于callout执行次数以及形式,如果仅是单次请求或者非并列形式,推荐使用httpcalloutMock方式,简单粗暴,而且自己造数据,不用上传静态资源,即使在其他环境下也可以正常跑,如果进行了多次请求,并且请求之间需要有并行操作那就只能使用multi callout 形式,使用此种方式记得在移到其他平台以前将静态资源上传。如果篇中有错误地方欢迎指正,有问题欢迎留言。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901