当前位置: 首页 > 知识库问答 >
问题:

Salesforce:web服务调用的APEX测试类

龙涵蓄
2023-03-14

我一直试图找出Web服务标注的测试类。我有四个不同的类。API_Member它包含所有参数以及字段的所有信息和匹配。我有一个API_Response类,我有一个Account tTriggerAccount tTriggerHandler

Account tTriggerHandler中,整个HTTPRequest和标注在我调用API_Member类的地方进行处理,然后从Account tTrigger触发它。

现在的困难是测试类,因为我不是一个有经验的开发人员。

我将如何管理此代码的测试类(我已经进行了更改,以防它是一些重要信息)?

public with sharing class AccountTriggerHandler {

    public void isAfterInsert(list<Account> accountNew) {
        for(Account a: accountNew) {
            sendData(a.Id);
        }
    }

    public void isAfterUpdate(list<Account> accountNew) {

    }

    @future(callout=true)
    public static void sendData(string accountId) {
        API_Member api = new API_Member(accountId);
        api.setupData();
        API_Member.Data data = api.dataList;
        string json = JSON.serialize(data); 
        system.debug('JSON' + json);
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        string url = 'http://api.XXXXXXXXXXXXXXXXXXXXXXX';
        string username = 'Ext-XXXXXXXXXXXXXXX-XXXXXXXXXXXXXX';
        string password = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
        request.setHeader('Authorization', authorizationHeader); 
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setEndpoint(url);
        request.setMethod('POST');
        request.setBody(json);
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 201 || response.getStatusCode() == 200 ) {
            API_Response responseCTRL = (API_Response) System.JSON.deserialize(response.getBody(), API_Response.class);
            list<API_Response.Meta> m = responseCTRL.Meta;
            System.debug('recordID='+m[0].recordID);
            api.setResponse(m[0].recordID,response.getStatus());
        }
    }
}

下面是API\U成员类

public class API_Member {
    public Data dataList;
    public Account input;
    public Contact c;
    public class Data {
        public list<Info> data;
    }
    public class Info {
            public String active;
            public String address_city;
            public String address_country;
            public String address_line_1;
            public String address_line_2;
            public String address_state;
            public String address_zipcode;
            public String company_name;
            public String date_end;
            public String date_paid;
            public String date_start;
            public String email;
            public String membership_number;
            public String mobile;
            public String org_number;
            public String person_first_name;
            public String person_last_name;
            public String person_number;
            public String phone;
            public String status;
            public String web_address;
    }

    public API_Member(string accountId) {
        this.input = getAccount(accountId);
        this.c = getContact();
    }

    public void setupData(){
        dataList = new Data();
        Info data = new Info();
        data.active = 'true'; //To be verified
        data.address_city = input.Ort__c;
        data.address_country = '';
        data.address_line_1 = input.Adress1__c;
        data.address_line_2 = '';
        //data.address_state = input.L_n_Namn__c;
        data.address_zipcode = input.Postnummer__c;
        data.company_name = input.Name;
        data.date_end = input.Expiry_Date__c != null ? string.valueOf(input.Expiry_Date__c) : '';
        data.date_paid = input.Last_Renew__c != null ? string.valueOf(input.Last_Renew__c) : '';
        data.date_start = input.Last_Renew__c != null ? string.valueOf(input.Last_Renew__c): '';
        data.email = input.Medlems_Epost__c;
        data.membership_number = input.AccountNumber;
        data.mobile = input.Phone;
        data.org_number = input.Organisationsnummer__c;
        data.person_first_name = c != null ? c.FirstName : '';
        data.person_last_name = c != null ? c.LastName : '';
        data.person_number = c != null ? c.Personnummer__c : '';
        data.phone = input.Phone;
        data.status = input.Status_Pay__c;
        data.web_address = input.Website;

        dataList.data = new list<Info>{data};
    }

    public Contact getContact(){
        list<Contact> c = [ SELECT Id,
                            Personnummer__c,
                            LastName,
                            FirstName
                            FROM Contact
                            WHERE AccountId =: input.Id
                            ORDER BY CreatedDate
                            ASC
                            LIMIT 1
        ];
        if(c.size() > 0){
            return c[0];
        }
        return null;
    }

    public Account getAccount(string accountId){
        Account a = [SELECT Id,
                    Ort__c,
                    Adress1__c,
                    Postnummer__c,
                    Name,
                    Expiry_Date__c,
                    Last_Renew__c,
                    Medlems_Epost__c,
                    AccountNumber,
                    Phone,
                    Organisationsnummer__c,
                    Status_Pay__c,
                    F_RecordId__c,
                    F_Satus__c,
                    Website
                    FROM Account
                    WHERE Id =: accountId
                    LIMIT 1
        ];
        return a;
    }
    
    public void setResponse(string recordId, string Status) {
        input.F_RecordId__c  = recordId;
        input.F_Satus__c  = status;
        update input;
    }
}

下面是API\U响应类

public class API_Response {

    public class Meta {
        public String recordID {get;set;} 
        public String href {get;set;} 
    }
    
    public List<Meta> meta {get;set;} 
    public List<Data> data {get;set;} 
    public Info info {get;set;} 
    public List<MetaField> metaField {get;set;} 
    
    public class MetaField {
        public String name {get;set;} 
        public Integer autoEntered {get;set;} 
        public Integer global_Z {get;set;} // in json: global
        public Integer maxRepeat {get;set;} 
        public String resultType {get;set;}         
    }
    
    public class Data {
        public String address_city {get;set;} 
        public String address_country {get;set;} 
        public String address_line_1 {get;set;} 
        public String address_line_2 {get;set;} 
        public String address_state {get;set;} 
        public String address_zipcode {get;set;} 
        public String company_name {get;set;} 
        public String date_end {get;set;} 
        public String date_start {get;set;} 
        public String email {get;set;} 
        public String membership_number {get;set;} 
        public String mobile {get;set;} 
        public String org_number {get;set;} 
        public String person_first_name {get;set;} 
        public String person_last_name {get;set;} 
        public String person_number {get;set;} 
        public String phone {get;set;} 
        public String status {get;set;} 
        public String upload_data_status {get;set;} 
        public String web_address {get;set;} 

    }
    
    public class Info {
        public String X_RESTfm_Version {get;set;} // in json: X-RESTfm-Version
        public String X_RESTfm_Protocol {get;set;} // in json: X-RESTfm-Protocol
        public Integer X_RESTfm_Status {get;set;} // in json: X-RESTfm-Status
        public String X_RESTfm_Reason {get;set;} // in json: X-RESTfm-Reason
        public String X_RESTfm_Method {get;set;} // in json: X-RESTfm-Method
        public String X_RESTfm_PHP_memory_limit {get;set;} // in json: X-RESTfm-PHP-memory_limit
        public String X_RESTfm_PHP_post_max_size {get;set;} // in json: X-RESTfm-PHP-post_max_size

    }
    
}

共有1个答案

赫连智
2023-03-14

对于单元测试,您必须模拟(伪造)您正在调用的服务。我们无法从单元测试调用真正的服务,因为:

  • 部署的成功/失败不应该取决于某个第三方服务器是否关闭
  • 您不会想在没有回滚方法的情况下向正式服发送“我的精彩测试数据!!!111”消息。

您需要编写一段代码,假装它就是那个服务。这取决于你,会有多棒。它总是可以返回相同的消息。或者,它可以检查接收到的数据,如果缺少必填字段,则抛出错误。真的吗?您决定,您最清楚应该测试多少个场景(您如何处理返回的错误?)

检查https://trailhead.salesforce.com/en/content/learn/modules/apex_integration_services/apex_integration_soap_callouts

嘲弄的整个概念也可以用于“正常”顶点,而不仅仅是标注。不过,这可能有点高级:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_stub_api.htm

编辑:

您需要2个可以标记为@isTest的类(因此它们不计入您的正常最大代码)。这是REST API,对吧?不是SOAP?也许https://trailhead.salesforce.com/content/learn/modules/apex_integration_services/apex_integration_rest_callouts会更好。在紧要关头,您可以将其设为1个类,但有点混乱,将它们分开?

首先进行API\U响应检查。它不必是全局的,公共的就足够了。类似于

@isTest
public class API_ResponseMock implements HttpCalloutMock {
    public HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('if you have sample JSON document that the service would return - paste it here. You must have something you used as the JSON2Apex input?');
        response.setStatusCode(200);
        return response;
    }

这是基础,您可能不希望它在每个“callout”上返回相同的内容,但已经足够好了。

AccountTriggerHandlerTest将是“正常”单元测试,创建测试帐户。类似于

@isTest
static void testCallout() {
    // Set mock callout class 
    Test.setMock(HttpCalloutMock.class, new API_ResponseMock());
    Test.startTest();
    insert new Account(Name = 'unit test'); // put whatever required fields you have
    Test.stopTest(); // @future's don't run until this line.

    // hm, what now? You have anything to "assert"? Will this callout be updating account maybe? Setting a Task with status=Completed, anything you can check?
}
 类似资料:
  • 下面是一个helper函数的代码 基本上,此方法只需使用HttpRequest和HttpResponse调用endpointURL,endpointURL是web服务,在参数中指定的超时之后,它将只返回200。 现在的问题是,我需要编写一个测试用例来涵盖这个方法,但我不知道如何编写它。。我不知道如何正确模拟httpcallout,因为此方法不返回HttpResponse,而且由于代码现在已冻结,我

  • 所以我是新来的salesforce,我完成了我的培训,现在我正在做一个项目。但是在我的项目中,我偶然发现了一个测试类,我没有找到编写它的方法,所以如果有人能帮我找到一种方法,我将不胜感激。这是代码: 此代码是一个触发器,当opportunity stage更改为“CloturéGagné”时,它会创建一个新的服务合同记录,其中包含从opportunity line items复制的合同行项目,在法

  • 我正在努力增加我在Android上的代码覆盖率。但我找不到测试这个演示者的正确方法。onSelectContact会进行一个服务调用,随后my ServiceFactory.GetContactService会进行另一个调用。我怎么能嘲笑这些电话呢?

  • 像组件一样,服务通常需要依赖,Angular通过服务类的构造函数注入。由于我们在Angular的引导过程之外初始化这些类,我们必须自己显式注入这些依赖。这是通过使用TestBed配置测试模块传回所需的依赖项(如HTTP模块)来实现的。

  • 问题内容: 我已经编写了带有远程接口的服务,并将其安装在PC的Eclipse AVD上。我有一个客户端测试工具,可以启动和调用服务中的方法。最初,我是通过控件类和活动安装的服务,现在已将其删除,因此该服务的清单如下所示: 因此没有活动标签。 当我从Eclipse中的调试图标启动它时,控制台会告诉我它正在安装apk(它确实是),但是它并没有作为调试线程出现,也没有触发断点,尽管该服务的行为到目前为止