0

This question already has an answer here:

I am trying to update the email in my Test class but it is not happening please help me.

This is my class-

global class PrepareSandboxPostCopy_Batch implements Database.Batchable {

String query;
String sObjectName;
Map <String, List <String>> sObjectEmaiLFieldsMap = new Map <String, List <String>>();

//Call this method from the class that implements the SandboxPostCopy Interface or from Developer console
global static void executeBatch() {
    Map <String, List <String>> sObjectEmaiLFieldsMap = getsObjectEmaiLFields();

    if(!sObjectEmaiLFieldsMap.isEmpty()) {
        Database.executeBatch(new PrepareSandboxPostCopy_Batch(sObjectEmaiLFieldsMap));
    }
}

/** BATCHABLE INTERFACE IMPLEMENTATION STARTS **/
global PrepareSandboxPostCopy_Batch(Map <String, List <String>> sObjectFieldsMap) {
    //Get First Key In Map
    sObjectName = new List<String> (sObjectFieldsMap.keySet()).get(0);

    sObjectEmaiLFieldsMap = sObjectFieldsMap;
    query = getSOQLString(sObjectName, sObjectEmaiLFieldsMap.get(sObjectName));
}

global Database.QueryLocator start(Database.BatchableContext BC) {
 //   system.debug('hellooo'+query);

    return Database.getQueryLocator(query);
}    

global void execute(Database.BatchableContext BC, List<sObject> scope) {

    for(sObject thisRecord : scope) {
        for(String thisField : sObjectEmaiLFieldsMap.get(sObjectName)) {
            String email = (String) thisRecord.get(thisField);
            if(String.isEmpty(email) || email.contains('.invalid') || email.contains('.noemail')) continue; //If empty or if contains .invalid then do not update
            thisRecord.put(thisField, email + '.invalid'); //Append invalid to the email
        }
    }
    Database.update(scope, false); //allow partial success
}

global void finish(Database.BatchableContext BC) {
    //Remove the sObject (First Key) once the records for the sObject processed successfully
    sObjectEmaiLFieldsMap.remove(sObjectName);
    executeBatch(sObjectEmaiLFieldsMap);
}
/** BATCHABLE INTERFACE IMPLEMENTATION ENDS **/

public static Boolean isSandbox() {
    return [SELECT IsSandbox FROM Organization WHERE Id =: UserInfo.getOrganizationId()].IsSandbox;
}

private static void executeBatch(Map <String, List <String>> sObjectFieldsMap) {
    if(!sObjectFieldsMap.isEmpty()) {
        Database.executeBatch(new PrepareSandboxPostCopy_Batch(sObjectFieldsMap));
    }
}

private static String getSOQLString(String sObjectName, List<String> sObjectFields) {

    String soqlQuery = 'SELECT {!sObjectFields} FROM {!objectTypeName} WHERE {!conditionals}';

    List<String> conditionals = new List <String>();
    for (String thisField: sObjectFields) { 
        conditionals.add(thisField + ' != NULL');
    }

    soqlQuery = soqlQuery.replace('{!sObjectFields}', String.join(sObjectFields, ' ,'));
    soqlQuery = soqlQuery.replace('{!objectTypeName}', sObjectName);
    soqlQuery = soqlQuery.replace('{!conditionals}', String.join(conditionals, ' OR '));

    if(!isSandbox()) soqlQuery = soqlQuery + ' LIMIT 0'; //For Non Sandbox (Production) Instance Do Not Update Records
    return soqlQuery;
}

//Get all Queryable Objects and it's email fields
private static Map <String, List <String>> getsObjectEmaiLFields() {

    Map <String, List <String>> sObjectEmailFieldMap = new Map <String, List <String>>();

    //Only pass the selected object, dynamically getting all objects may exceed APEX CPU Limit
    List<SObjectType> sObjectsToUpdate = new List<SObjectType>{ Account.SObjectType, 
                                                                Contact.SObjectType, 
                                                                Case.SObjectType, 
                                                                CampaignMember.SObjectType, 
                                                                Lead.SObjectType, 
                                                                Opportunity.SObjectType, 
                                                                Quote.SObjectType };

    for(SObjectType sObjectType : sObjectsToUpdate) {

        //Describe sObject
        DescribeSObjectResult sObjectDescribe = sObjectType.getDescribe();

        String objectTypeName = sObjectDescribe.getName();

        //Skip objects we cannot query or update
        if(!sObjectDescribe.isQueryable() || !sObjectDescribe.isUpdateable()) continue;

        for(SObjectField sObjectField: sObjectDescribe.fields.getMap().values()) {

            DescribeFieldResult thisField = sObjectField.getDescribe();

            //Skip all non email fields
            if(thisField.getType() != Schema.DisplayType.EMAIL || !thisField.isFilterable() || !thisField.isUpdateable()) continue;

            if(sObjectEmailFieldMap.containsKey(objectTypeName)) {
                sObjectEmailFieldMap.get(objectTypeName).add(thisField.getName());
            }
            else {
                sObjectEmailFieldMap.put(objectTypeName, new List <String> {thisField.getName()});
            }
        }
    }
    return sObjectEmailFieldMap;
}

}

This is my test class --

@isTest private class SandboxPostRefreshTestCase {

static testMethod void testMethod1() { Map > sObjectEmailFieldMap = New Map >(); Account accVar = new Account(); accVar.Name ='Account Test'; INSERT accVar;

    Contact conVar = new Contact();
    conVar.LastName ='Contact Test';
    conVar.AccountId =accVar.Id;
    conVar.Email = 'test@gmail.com';
    conVar.Other_Email__c = 'testother@gmail.com';
    INSERT conVar;

    Case casVar = new Case();
    casVar.Origin ='Email';
    casVar.Status = 'New';
    // casVar.ContactEmail = 'test@gmail.com';
    casVar.SuppliedEmail = 'testother@gmail.com';
    INSERT casVar;

    Campaign  camVar = new Campaign();
    camVar.Name ='test';
    INSERT camVar;

    CampaignMember newMemberVar = new CampaignMember();
    newMemberVar.CampaignId = camVar.Id;
    newMemberVar.ContactId = conVar.Id;
    // newMember.Email = 'test@gmail.com';
    INSERT newMemberVar;

    Lead leadVar = new Lead();
    leadVar.LastName = 'testsds';
    leadVar.Status = 'New';
    leadVar.Company = 'test';
    leadVar.Email = 'test@gmail.com';
    INSERT leadVar;

    Opportunity oppVar = new Opportunity();
    oppVar.Name = 'testsds';
    oppVar.AccountId = accVar.Id;
    oppVar.CloseDate = date.today();
    oppVar.StageName = 'Proposal';
    INSERT oppVar;

    Quote quoteVar = new Quote();
    quoteVar.Name = 'testsds';
    // quoteVar.Account = accVar.Id;
    quoteVar.OpportunityId = oppVar.Id;


    Test.startTest();

    Map<String, List<String>> sObjectFieldsMap = new Map<String, List<String>>();
    sObjectFieldsMap.put('Contact', new List<String>{'Email'});  
   // sObjectFieldsMap.put('Lead', new List<String>{'Email'});  

    PrepareSandboxPostCopy_Batch obj = new PrepareSandboxPostCopy_Batch(sObjectFieldsMap);
    PrepareSandboxPostCopy_Batch.executeBatch();
    Id batchId = Database.executeBatch(obj);


    Contact ldVar = [Select Id, LastName, Email FROM Contact WHERE Id =: conVar.Id];
    system.debug('Contact ldVar Email'+ldVar.Email);
    //system.assertEquals('test@gmail.com.invalid', ldVar.Email);

    Test.stopTest(); 
}

}

when i debug my test email value it is not giving me right value please help me

marked as duplicate by Reshma, David Reed apex Jan 11 at 12:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Move the Test.stopTest(); line to immediately after the Database.executeBatch(obj);. The batch job will be processed on the stopTest line. Then you can query for the results and make assertions that it worked as expected. – Daniel Ballinger Jan 11 at 8:12
  • Thank you so much for replying me no it works fine but when I add sObjectFieldsMap.put('Contact', new List<String>{'LastName,Email'}); this It gives me wrong query in PrepareSandboxPostCopy_Batch query variable – Lokesh Malviya Jan 11 at 8:16
  • I didn't get you – Lokesh Malviya Jan 11 at 9:30
  • Please do not blank out question content. I have rolled this change back. – David Reed Mar 13 at 11:49