Salesforce测试Web服务电话

时间:2018-09-23 03:37:30

标签: salesforce

这是帮助函数的代码

public class SalesforceHelper {
    public static void waitCall(String timeout){
        System_Settings__c lnpSetting = System_Settings__c.getValues('System Properties');
        String endpoint=lnpSetting.Base_Endpoint_URL__c + 'salesforceHelper/wait?timeout=' + timeout;
        system.debug('====endpoint======'+endpoint);
        HttpRequest httpReq=new HttpRequest();  
        HttpResponse httpResp = new HttpResponse(); 
        Http http = new Http();
        httpReq.setMethod('GET'); 
        httpReq.setEndpoint(endpoint);
        String username=lnpSetting.Endpoint_Username__c;
        String password=lnpSetting.Endpoint_Password__c;    
        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue); 
        httpReq.setHeader('Authorization', authorizationHeader); 
        httpReq.setHeader('content-type','application/json; charset=utf-8');
        httpReq.setTimeout(120000);
        try{
            httpResp = http.send(httpReq);
            System.debug('Wait response' + httpResp);
        } catch (Exception e) {
            system.debug(LoggingLevel.Error, 'Error HTTP response code = ' + httpResp.getStatusCode() + '; calling '+endpoint );
        }
    }
}

基本上,此方法仅使用HttpRequest和HttpResponse调用终结点URL,并且终结点URL是Web服务,并且它将在参数指定的超时后仅返回200。

现在的问题是,我需要编写一个测试用例来涵盖此方法,并且我不知道如何编写该方法。.我不知道如何正确地模拟httpcallout,因为该方法没有返回HttpResponse,由于代码现在已冻结,因此我无法修改类以使测试用例正常工作。

还有其他方法可以为此方法创建测试类吗?

1 个答案:

答案 0 :(得分:0)

您绝对应该能够使用标准的Http Callout Mock:

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

唯一的区别是您只需设置统计代码:

// Create a fake response
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
return res;

并检查响应代码:

System.assertEquals(200, res.getStatusCode());