Плохое покрытие кода для тестового класса услуг входящей электронной почты Apex - PullRequest
0 голосов
/ 30 ноября 2018

Наше требование заключается в обработке входящей электронной почты с определенного адреса электронной почты и создании дела.Мой класс работает нормально, но тестовый класс очень плохой с охватом кода всего 10%.Кто-нибудь может мне помочь, пожалуйста.У меня нет проблем с обработкой писем, но я не могу преуспеть в тестовом классе.Спасибо!

*** Apex Email services class***

global Class EtoCkroger implements Messaging.InboundEmailHandler {

// Instantiate variables that we will need for handling this email

String location;
String problem;
Integer locationIdx;
Integer problemIdx;
String locationFinal;
String needFinal;
String serviceFinal;
String tradeFinal;
String InboxFinal;
String initiatorFinal;
String TimeFinal;
String poFinal;
String phoneFinal;
String warrantyFinal;
String descriptionFinal;
String orderFinal;
String criticalFinal;
String productFinal;   
String problemFinal;
String machineFinal;
String krogerFinal;
String siteFinal;
global Messaging.InboundEmailResult handleInboundEmail
           (Messaging.InboundEmail email, Messaging.InboundEnvelope envelope){  
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
 if (email.fromaddress =='shashank.sfdev@gmail.com') //// Kroger locations 
               {

String[] bodySplitted = email.PlainTextBody.split('\n');


krogerFinal = email.subject.substringAfter(')').normalizespace();
poFinal = email.plainTextBody.substringBetween('Call/Action #' , 'Call/Action Type/Status').remove('*').remove('(Include this # on Invoice)').normalizespace();
initiatorFinal = email.plainTextBody.substringBetween('Point of Contact', 'Billing Address').remove('*').normalizespace(); 
tradeFinal = email.plainTextBody.substringBetween('Symptom' , 'Notes').remove('*').normalizespace();
problemFinal = email.plainTextBody.substringBetween('Notes' , 'Service Window').remove('*').remove('Service Requirements:').normalizespace(); 
criticalFinal = email.plainTextBody.substringBetween('Severity' , 'Service').remove('*').normalizespace();
productFinal = email.plainTextBody.substringBetween('Product' , 'Symptom').remove('*').trim();
orderFinal = email.plainTextBody.substringBetween('Service Window' , 'Start Date/Time').remove('*').normalizespace();
inboxFinal = email.plainTextBody.substringBetween('Start Date/Time' , 'Respond By').remove('*').normalizespace();
timeFinal = email.plainTextBody.substringBetween('Respond By' , 'Complete By').remove('*').normalizespace();
needFinal = email.plainTextBody.substringBetween('Complete By' , 'Please open').remove('*').remove('Special Instructions:').remove('-').normalizespace();                   
descriptionfinal = 'Product: ' + productFinal + '\n' + 'Service Window: ' + orderFinal + '\n' + 'Start Date/Time: ' + inboxFinal + '\n' + 'Respond By: ' + timeFinal + '\n' + 'Complete By: ' + needFinal;                    

Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Service - Managed Service Case').getRecordTypeId();
Id rtId = RecordTypeIdCase;                

system.debug('productFinal: ' +productFinal);
system.debug('tradeFinal: ' +tradeFinal);
system.debug('poFinal: ' +poFinal);
system.debug('orderFinal: ' +orderFinal);
system.debug('krogerFinal: ' +krogerFinal);
system.debug('problemFinal: ' +problemFinal);
system.debug('initiatorFinal: ' +initiatorFinal);
system.debug('descriptionfinal: ' +descriptionfinal);
if (krogerFinal != NULL) {
    SVMXC__Site__c [] locArray = [Select Id, Name, SVMXC__Site_Phone__c, SVMXC__Account__r.Id from SVMXC__Site__c where NTT_Legacy_Location_ID__c = :krogerFinal];
            try{      

case c= new case();
c.subject= 'BUNNSERVE REQUEST';
c.Case_Type__c= 'Service Request';
c.Origin='Email';
c.Status='new';
c.AccountId = locArray[0].SVMXC__Account__r.Id;
c.SVMXC__Site__c = locArray[0].Id;  
c.RecordTypeId = rtId;    
c.Description= 'Symptom: ' + tradeFinal + '\n' + 'Notes: ' + problemFinal + '\n' + 'Severity: ' + criticalFinal +  + '\n' + descriptionfinal; 
c.KA_PO__c= poFinal;
c.Location_Contact_Name__c = InitiatorFinal; 
c.BSP_Location_Contact_Phone__c = locArray[0].SVMXC__Site_Phone__c;
c.OwnerId = '00G0x000000K0J3';

insert c; 
}
catch(System.dmlException e)
     {System.debug('Error: Unable to create new Case: ' + e);
     }         

              }
        else if (krogerFinal == null){
              System.debug('No location was found');    
        }

    }   
return result;

      } // Close handleInboundEmail ()
}

Ниже приведен текстовый класс

@istest 
public class TestEtoCKroger {
    static testMethod void TestEtoCKroger () {


       // create a new email and envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail() ;
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();           

Map<ID,Schema.RecordTypeInfo> rt_Map = Case.sObjectType.getDescribe().getRecordTypeInfosById();
        Id RecordTypeIdCase = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Service - Managed Service Case').getRecordTypeId();
        Id rtId = RecordTypeIdCase;                

   Account acc = new Account();
        acc.Name = 'Test Account';
        acc.BillingStreet = '123  St.';
        acc.BillingCity = 'Springfield';
        acc.BillingState = 'IL';
        acc.BillingPostalCode = '62704';
        insert acc;

    SVMXC__Site__c loc = new SVMXC__Site__c();
       loc.Name = 'Sample Test';
       loc.NTT_Metro_Remote__c = 'Zone A';
       loc.SVMXC__Street__c = '123 E Main St.';
       loc.SVMXC__City__c = 'Springfield';
       loc.SVMXC__State__c = 'ILLINOIS';
       loc.SVMXC__Zip__c = '62511';
       loc.SVMXC__Country__c = 'United States';
       loc.NTT_Legacy_Location_ID__c = 'Sample Test';   
       loc.SVMXC__Account__c = acc.Id;
       loc.BSP_Location_Contact_Phone__c = '111 222 1343';
       insert loc;
Case cse = new  CASE(
   Subject = 'Test Subject',
   Description = 'Test description',
   Origin = 'Email',
   SVMXC__Site__c = loc.Id,
   Status = 'New',
   recordtypeid = rtId,
   accountid= acc.Id,
   KA_PO__c = '1001',
   BSP_Location_Contact_Phone__c = '111 222 3443',
   Case_Type__c = 'Service Request',
   Location_Contact_Name__c = 'Test Man'

);
insert cse;
       // setup the data for the email
     email.subject = 'Kroger Service Call Notification 10935174/1 (HIGH) Sample Test';
     env.fromAddress = 'someaddress@email.com';
     email.plainTextBody = 'email body for testing';


      EtoCKroger TestEtoCKroger=new EtoCKroger ();
      TestEtoCKroger.handleInboundEmail(email, env);
    Messaging.InboundEmailResult result = TestEtoCKroger.handleInboundEmail(email, env);
System.assertEquals( result.success , true);

Case[] c = [select id, SVMXC__site__r.id, SVMXC__Site__c, recordtypeid,  KA_PO__c, Location_Contact_Name__c, description, BSP_Location_Contact_Phone__c, subject, Case_Type__c, Origin, Status, Account.Name, account.id from Case where SVMXC__Site__c = :loc.Id limit 1]; 
 system.debug('TestEtoCKroger: [' + TestEtoCKroger + ']' );

    if(c.size() > 0)

System.assertEquals(c[0].SVMXC__Site__c, loc.Id);
System.assertEquals(c[0].account.Id, acc.Id);
System.assertEquals(c[0].recordtypeId, 'rtId');
System.assertEquals(c[0].KA_PO__c, '1001');
System.assertEquals(c[0].Location_Contact_Name__c, 'Test Man');       
System.assertEquals(c[0].BSP_Location_Contact_Phone__c, '111 222 3443');
System.assertEquals(c[0].subject, 'Test Subject');
System.assertEquals(c[0].Case_Type__c, 'Service Request'); 
System.assertEquals(c[0].Origin, 'Email');
System.assertEquals(c[0].Status, 'New');  
System.assertEquals(c[0].description, 'Test description');  
 update c;      


    }     

}

А ниже приведен типовой шаблон от нашего клиента.Я должен разобрать тело письма и создать дело.

**Assignment Information:**

Call/Action #                   00035174 / 1 (Include this # on Invoice)
Call/Action                     Type/Status Test data
Service Center                  021 - Central 
Attention                       TEST CORP

**Customer Details:**
Location                        Store 990
Street Address                  1111 Lane; Ft. Wayne, CA 46804
Point of Contact                Store Manager    
Billing Address                 5960 S Drive;Indianapolis,IN 46100
Billing Phone                   111-523-4601

**Service Call Details:**
Severity            HIGH
Service             Product 
Product             PREP EQUIPMENT 
EquipNo: N/A
SerialNo:N/A
AssetNo: N/A
Symptom             Poor performance
Notes               Test notes.

**Service Requirements:**
Service Window      No Service window define
Start Date/Time     26 JUL 2018 16:07
Respond By          N/A
Complete By         23 AUG 2018 16:07

**Special Instructions:**
Please open the attached Acknowledge.html attachment and accept the service call with an ETA or reject with the appropriate reason.
Before beginning any work in our store please check in at CUSTOMER SERVICE.
Please present company identification and the Service Hub call number to which this visit is in response.
...