Salesforce 编写 Future Method 的测试类 - 覆盖率 28%

问题描述 投票:0回答:1

我有一个类,我正在尝试调用 HTTP 请求。我创建了一个模拟测试和一个测试类。

我的测试类成功,代码覆盖率达到 28%,但无法识别我在类中使用的调用方法,下面是代码

我的班级-

    public class PD_WelcomeMaroPost {
       
        @future(callout=true)
        public static void sendEmailThroughMaro(string myInpEmail) {
            string successContacts = '';
            string failureContacts = '';
            
            List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
            //List<Case> newCase = new List<Case>();
            
            
            // SQL to fetch FBO who Joined Today
            list<Account> conts = new list<Account> ([SELECT Id, name, Email_FLP_com__c,
                                                    (SELECT Id FROM Stripe_Subscriptons__r WHERE Start_Date__c= TODAY
                                                    AND Status__c='active'
                                                    AND Welcome_Email__C = false LIMIT 1)from account
                                                    where ID IN (select Distributor__c from Stripe_Subscripton__c
                                                    where Start_Date__c= TODAY AND Status__c='active'
                                                    AND Welcome_Email__C = false)
                                                    AND  Email_FLP_com__c != NULL LIMIT 100]);
                
            system.debug('>>>>>>>>>>' + conts);
            overallEmail myEmail = new overallEmail();
           
            for(Account c : conts){
               string resultBodyGet = '';
                myEmail.email.campaign_id = 172;
                
                myEmail.email.contact.Email = c.Email_FLP_com__c;
                myEmail.email.contact.first_name = c.name;
                
                /**MAp<String, String> tags = new Map<String, String>();
                tags.put('firstName', c.name);
                myEmail.email.tags = tags;**/
                system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
                
                
                try{
                    String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
                    HttpRequest req = new HttpRequest();
                    req.setEndpoint(endpoint);
                    req.setMethod('POST');
                    req.setHeader('Content-type', 'application/json');
                    req.setbody(JSON.serialize(myEmail));
                    Http http = new Http();
                    system.debug('Sending email');
                    HTTPResponse response = http.send(req); 
                    system.debug('sent email');
                     resultBodyGet = response.getBody();
                    system.debug('Output response:' + resultBodyGet);
                    maroResponse myMaroResponse = new maroResponse();
                    myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
                    system.debug('#### myMaroResponse: ' + myMaroResponse);
                    if(myMaroResponse.message == 'Email was sent successfully')
                       successContacts = successContacts + ';' + c.Email_FLP_com__c;
                    else
                        failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
                }
                catch (exception e) {
                    failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
                    system.debug('#### Exception caught: ' + e.getMessage());                
                }
                
                c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
                c.Stripe_Subscriptons__r[0].Welcome_Email_Sent_Date__c = system.today();
                subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
               
            }
           
            Update subsToUpdate;
                  
        }
        
        public class maroResponse {
            public string message {get;set;}
        }
    
        public class overallEmail {
            public emailJson email = new emailJson();
        }
        
        public class emailJson {
            public Integer campaign_id;
            
            public contactJson contact = new contactJson();
           //Public Map<String, String> tags;
        }
        
        public class contactJson {
            public string email;
            public string first_name;
        }
       
    }

我的 MockTest 类 - 我使用这个 Mockclass 来生成 Mock 响应。该文档没有测试方法,因此使用相同的格式

    @isTest
    Global class PD_WelcomeMaroPostMock implements HttpCalloutMock {
        Global HttpResponse respond(HttpRequest req) {
            // Create a fake response
            // 
          
            //System.assertEquals(JSON.serialize(myEmail),req.getbody());
            
            HttpResponse res = new HttpResponse();
            res.setHeader('Content-Type', 'application/json');
            res.setBody('{"status":"success"}');
            res.setStatusCode(200);
            return res; 
        }
    }

这是我的测试类 - 这是我用于响应的类。我的插入作业成功,但我的 HTTP 响应失败。

    @IsTest
    private class PD_WelcomeMaroPost_test {
        
        public class overallEmail {
            public emailJson email = new emailJson();
        }
        public class emailJson {
            public Integer campaign_id;
            
            public contactJson contact = new contactJson();
        }
        public class contactJson {
            public string email;
            public string first_name;
        }
        
        @IsTest
        private static void testemail() {
            
            overallEmail myEmail = new overallEmail();
            Account a = new Account();
            a.Name ='Test' ;
            a.Email_FLP_com__c = '[email protected]';
            insert a ; 
            
            Stripe_Subscripton__c s = new Stripe_Subscripton__c();
            
            // insert subscription --
            s.Distributor__c = a.Id;
            S.Welcome_Email__c = TRUE;
            S.Welcome_Email_Sent_Date__c = system.today();
            s.Subscription_Id__c = 'sub_9H0LLYFZkekdMA' ; 
            INSERT S;
            
            Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
            String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
            HttpRequest req = new HttpRequest();
            req.setEndpoint(endpoint);
            req.setMethod('POST');
            req.setHeader('Content-type', 'application/json');
            req.setbody(JSON.serialize(myEmail));
            
            
            Test.startTest();
            
            PD_WelcomeMaroPost.sendEmailThroughMaro('[email protected]');
            
            Test.stopTest();
            
        }
        
    }
salesforce apex-code apex force.com
1个回答
0
投票

当我自己声明一个Mock时,我在测试启动事务中声明它:

Test.startTest();

Test.setMock(WebServiceMock.class, new WebServiceMockImpl());

// Rest of test code here

Test.stopTest();

还在您的测试类中,您似乎只构建了 HTTP 请求而不发送它,请尝试添加以下内容:

HttpResponse res = http.send(req);

if (res.getStatusCode() == 200) { } else { }
© www.soinside.com 2019 - 2024. All rights reserved.