0

我正在处理 Salesforce 批处理类,当批处理失败时应该向我发送电子邮件。目前,无论状态如何,它都会在批处理运行完成时发送电子邮件。

测试失败并断言电子邮件未按预期发送:

Error: System.AssertException: Assertion Failed: Email Not sent

主类:

public with sharing class BatchToUpdateIPiSeq extends ilib_ScheduleAndBatch implements Schedulable, Database.Stateful{
  public static final Integer IP_UP_GRACE_PERIOD = 90;
  public static final Integer IP_UP_GRACE_PERIOD  = 120;
  public static final string CODEPARAMETERNAME = 'Product_Code_for_IP';
  public Set<String> setNonUpdatedIPErrors = new Set<String>();
  @TestVisible static boolean boolEmailSent= false;
  public static Boolean boolIsTestRunning = false;


/*
*  Description: Execute method to be called when class is scheduled
*/
public override void execute(SchedulableContext ctx)
{
    integer intDefaultBatchsize = 1;
    Map < String, String > params = UtilsSettings.getCustomMetadataMap('Schedule_Batch_for_iSeq');
    Integer batchSize = UtilsSettings.parseIntegerFromSettingsMap(params, 'BatchiSeq', intDefaultBatchsize);
    
    if (batchSize < 1 || batchSize > 100) {
        batchSize = intDefaultBatchsize;
    }
    Database.executebatch(new BatchToUpdateIPiSeq(), batchSize);
    
}
/*
* Description: Fetch required installed products to process
*/
public override Database.QueryLocator start(Database.BatchableContext bc) {
    string strQuery;
    Date dtDueDate = Date.Today()-IP_UP_GRACE_PERIOD_ILMN;
    Set<String> productCode = new Set<String>();
    CodeParametersSelector codeParameterSlctr = new CodeParametersSelector();
    List<Code_Parameter__mdt> objCodeParam = codeParameterSlctr.selectCodeParameterByDeveloperName(new Set<String>{CODEPARAMETERNAME});
    productCode.addAll(objCodeParam[0].Value__c.split(';'));
    strQuery = 'SELECT Id, SVMXC__Company__c, Name, Operation_Status__c, SVMXC__Status__c, Acceptance_Date__c, SVMXC__Date_Installed__c, SVMXC__Date_Shipped__c FROM SVMXC__Installed_Product__c WHERE Product_Code__c IN:productCode AND SVMXC__Status__c = \'Shipped\' AND Operation_Status__c != \'On\' AND Acceptance_Date__c = NULL AND SVMXC__Date_Installed__c = NULL AND  SVMXC__Date_Shipped__c<:dtDueDate';
    return Database.getQueryLocator(strQuery);
}
/*
* Process the qualified records as batchs
*/
public void execute(Database.BatchableContext bc, List<SVMXC__Installed_Product__c> lstIP){
    set<Id>setAccId  = new set<Id>();
    for(SVMXC__Installed_Product__c objectIP : lstIP){
        setAccId.add(objectIP.SVMXC__Company__c);
    }
    List<ObjectTerritory2Association>listCPAccId = new ObjectTerritory2AssociationsSelector().selectIndirectByAccountIds(setAccId);
    map<id, ObjectTerritory2Association>mapIPobjTerritory = new map<id,ObjectTerritory2Association>();
    for(ObjectTerritory2Association ota : listCPAccId){
        mapIPobjTerritory.put(ota.ObjectId, ota);
    }
    for(SVMXC__Installed_Product__c objIP : lstIP){
        Date dtStartDate = objIP.SVMXC__Date_Shipped__c;
        Date dtDueDate = Date.Today();
        Integer numberDaysDue = dtStartDate.daysBetween(dtDueDate);
        
        if( mapIPobjTerritory.containsKey(objIP.SVMXC__Company__c)){
            if(numberDaysDue>IP_UP_GRACE_PERIOD_CP){
                objIP.Operation_Status__c = 'On';
                objIP.SVMXC__Status__c = 'Installed';
                objIP.Acceptance_Date__c = system.today();
                objIP.SVMXC__Date_Installed__c = system.today();
            }
        }else{
            objIP.Operation_Status__c = 'On';
            objIP.SVMXC__Status__c = 'Installed';
            objIP.Acceptance_Date__c = system.today();
            objIP.SVMXC__Date_Installed__c = system.today();
            
        }
    }
    
    if(!lstIP.isEmpty()){
        Database.SaveResult[] result = Database.update(lstIP, false);
        Integer intCount = 0;
        for (Database.SaveResult sr : result){
            if(!sr.isSuccess()){
                for(Database.Error err : sr.getErrors()){
                    setNonUpdatedIPErrors.add(lstIP.get(intCount).id +' : '+ err.getStatusCode() + ': ' + err.getMessage()+ ': ' + err.getFields());
                }
            }
            intCount++;
        }
    }
    
    
}
/*
* Finish Method
*/
public override void finish(Database.BatchableContext bc){
    if(!setNonUpdatedIPErrors.isEmpty() || !boolIsTestRunning){
        CodeParametersSelector codeParameterSlctr = new CodeParametersSelector();
        List<Code_Parameter__mdt> objCodeParam = codeParameterSlctr.selectCodeParameterByDeveloperName(new Set<String>{'SFDC_Service_Email_Id'});
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        List<String> strEmailId = new List<String>();
        if(!Test.isRunningTest()){
            strEmailId.addAll(objCodeParam[0].Value__c.split(';'));
        }
        else{
            strEmailId.add('hshukla@illumina.com');
        }
            
        email.setToAddresses(strEmailId);
        String subject = 'ACTION NEEDED: Installed Product (iSeq/Dragen) update failed';
        email.setSubject(subject);
        String strBody = 'Following Installed Prodcut were not updated : </br>';
        for(String str : setNonUpdatedIPErrors){
            strBody = strBody + str+'</br>';
        }
        email.setHtmlBody(strBody);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        boolEmailSent = true;
    }
}

测试类:

@isTest(SeeAllData=false)
public class TestBatchToUpdateIPiSeq {
public static final String NULL_Operation_STATUS = null;
public static final Date NULL_ACCEPTANCE_DATE = null;
public static final Date NULL_DATE_INSTALLED = null;
public static final String STRING_PRODUCT_CODE_iSEQ = '20021532';
public static final string CODEPARAMETERNAME = 'Product_Code_for_IP';
public static boolean updatedRecords;
static testmethod void testIPiSeq(){
    
   List<Territory2>listCPAccId = [SELECT Id FROM Territory2 WHERE Territory2Type.DeveloperName = 'Territory_Channel_Partner' AND Territory2Model.State = 'Active'];
    
    Account acc = TestDataAccount.getAccount('Test Acc', 'USD');
    acc.Account_Group__c='Distributor';
    insert acc;
    
    ObjectTerritory2Association objOTA = TestDataObjectTerritory2Association.getObjectAssociation(listCPAccId[0].Id,acc.Id);
    insert objOTA;
    List<String> productCode = new List<String>();
    CodeParametersSelector codeParameterSlctr = new CodeParametersSelector();
    List<Code_Parameter__mdt> objCodeParam = codeParameterSlctr.selectCodeParameterByDeveloperName(new Set<String>{CODEPARAMETERNAME});
    productCode.addAll(objCodeParam[0].Value__c.split(';'));
    Product2 objProduct = new Product2(Name = 'testProduct',Service_Product_Type__c = 'Core');
    objProduct.ProductCode = productCode[0];
    insert objProduct;
    
    SVMXC__Installed_Product__c objInstalledProduct = TestDataFieldService.createInstalledProduct('TestIP', 'USD', 'Shipped');
    SVMXC__Installed_Product__c objInstalledProduct1 = TestDataFieldService.createInstalledProduct('TestIP', 'USD', 'Shipped');
    objInstalledProduct.SVMXC__Company__c = acc.Id;
    objInstalledProduct1.SVMXC__Company__c = acc.Id;
    objInstalledProduct.SVMXC__Product__c=objProduct.id;
    objInstalledProduct1.SVMXC__Product__c=objProduct.id;
    objInstalledProduct.SVMXC__Date_Shipped__c = Date.newInstance(2020, 11, 01);
    objInstalledProduct1.SVMXC__Date_Shipped__c = Date.newInstance(2020, 11, 30);
    objInstalledProduct.Operation_Status__c = NULL_Operation_STATUS;
    objInstalledProduct1.Operation_Status__c = NULL_Operation_STATUS;
    objInstalledProduct.Acceptance_Date__c = NULL_ACCEPTANCE_DATE;
    objInstalledProduct1.Acceptance_Date__c = NULL_ACCEPTANCE_DATE;
    objInstalledProduct.SVMXC__Date_Installed__c = NULL_DATE_INSTALLED;
    objInstalledProduct1.SVMXC__Date_Installed__c = NULL_DATE_INSTALLED;
    insert new List<SVMXC__Installed_Product__c>{objInstalledProduct, objInstalledProduct1}; 
    BatchUpdateQSR.boolIsTestRunning = true;
    Test.StartTest();
    Database.executeBatch(new BatchToUpdateIPiSeq());  
    String sch = '0 0 0 * * ?';
    System.schedule('BatchToUpdateIPiSeq', sch, new BatchToUpdateIPiSeq()); 
    Test.StopTest();
    updatedRecords = true;
    
    List<SVMXC__Installed_Product__c> listIP = new List<SVMXC__Installed_Product__c>([Select Name, Operation_Status__c, SVMXC__Status__c from SVMXC__Installed_Product__c Where Id=:objInstalledProduct.id]);
    //system.assertEquals('On',listIP[0].Operation_Status__c);
    for(SVMXC__Installed_Product__c objIP : listIP){
        if(objIP.Operation_Status__c!='On'){
            updatedRecords = false;
        }
    }
    System.assert((BatchToUpdateIPiSeq.boolEmailSent),'Email Not sent');
    System.assertEquals(true,updatedRecords);
  }
}
4

0 回答 0