• Procurement Executive
  • NEWBIE
  • 0 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 6
    Questions
  • 5
    Replies
Need help with test class for @invocablemethod
Apex Class:-
public class SurveyResponseUpdate{
    
    @InvocableMethod
    public static void updateContactWithResponse(List<Id> ResId){
        set<Id> ConId = new set<Id>();
        set<Id> UserId = new set<Id>();
        map<Id, String> contactMap = new map<Id, String>();
        for(SurveyQuestionResponse surveyRes:[SELECT id, QuestionId, ResponseId, Response.SubmitterId, 
                                              QuestionChoiceId, Question.Name, QuestionChoice.Name
                                              FROM SurveyQuestionResponse
                                              WHERE Id =: ResId])
        {
            if(surveyRes.Response.SubmitterId != null 
               && string.valueOf(surveyRes.Response.SubmitterId).startswith('003')
               && surveyRes.Question.Name == 'How many employees are in your organization?')
            {
                contactMap.put(surveyRes.Response.SubmitterId, surveyRes.QuestionChoice.Name);
            }
        }
        
        List<Account> acclisttoUpdate = new List<Account>();
        
        for(Contact con:[SELECT Id, AccountId FROM Contact WHERE Id IN :contactMap.keyset() AND AccountId != NULL])
        {
            acclisttoUpdate.add(new Account(id = con.accountid, Number_of_Employees__c = contactMap.get(con.Id)));
        }
        
        if(acclisttoUpdate.size() > 0){
            update acclisttoUpdate;
        }
    }
}

Test Class:-
@isTest
private class Test_SurveyResponseUpdate {
    private static testMethod void doTest() {
        
        Account testAccount = new Account();
        testAccount.Name='Test Account' ;
        insert testAccount;
        
        List<Account> listAccount = new List<Account>();
        update listAccount;
         
        Contact cont = new Contact();
        cont.FirstName='Test';
        cont.LastName='Test';
        cont.Accountid= testAccount.id;
        insert cont;
        
        List<Contact> listCont = new List<Contact>();
        
        SurveyQuestion survQuestion = new SurveyQuestion();
        
        SurveyResponse survResponse = new SurveyResponse();
                
        SurveyQuestionChoice survQuestChoice = new SurveyQuestionChoice();
        
        Test.startTest();
            List<SurveyQuestionResponse> survQuestResponse = new List<SurveyQuestionResponse>();
            List<id> listId= new List<id>();
            SurveyResponseUpdate.updateContactWithResponse(listId);
        Test.stopTest();

        
    }
}

I am getting 52% coverage. 
Apex Class:- 
/**
 * Created by usman on 1/30/2020.
 */

global class CampaignEmailUtility{
    public static void createListEmail(String fuStageId){
        Campaign_Follow_Up_Stage__c objCFUS = CampaignEmailUtility.getFollowUpStage(fuStageId);        
        if(objCFUS != null) {
            OrgWideEmailAddress owdEmail = CampaignEmailUtility.getEmailById(objCFUS.Campaign__r.From_Email_Id__c);
            EmailTemplate objEmailTemplate = CampaignEmailUtility.getEmailTemplateById(objCFUS.Email_Template_Id__c);
            ListEmail objLeadEmail = new ListEmail(
                Status='draft',
                CampaignId = objCFUS.Campaign__c,
                FromAddress = owdEmail.Address,//'awsqualitytech@gmail.com',
                FromName = owdEmail.DisplayName,//'Chris Taylor',
                HtmlBody = objEmailTemplate.HtmlValue,
                Name = objEmailTemplate.Subject,
                Subject = objEmailTemplate.Subject,
                TextBody = objEmailTemplate.Body
            );
            insert objLeadEmail;
            CampaignEmailUtility.createListEmailRecipientSource(objLeadEmail.Id, objCFUS.Campaign__c);
        }
    }

    public static OrgWideEmailAddress getEmailById(String oId){
        return [select Id,Address,DisplayName from OrgWideEmailAddress WHERE Id = :oId limit 1];
    }
    public static EmailTemplate getEmailTemplateById(String templateId){
        list<EmailTemplate> objEmailTemplates = [SELECT Body,BrandTemplateId,Description,DeveloperName,Encoding,
                                                    EnhancedLetterheadId,FolderId,FolderName,HtmlValue,Id,IsActive,
                                                    Markup,Name,NamespacePrefix,OwnerId,RelatedEntityType,Subject,
                                                    TemplateStyle,TemplateType,TimesUsed,UiType
                                                FROM EmailTemplate WHERE Id=:templateId];
        if(objEmailTemplates != null){
            return objEmailTemplates.get(0);
        }
        return null;
    }

    public static Campaign_Follow_Up_Stage__c getFollowUpStage(String fuStageId){
        list<Campaign_Follow_Up_Stage__c> objFollowUpStage = [SELECT Id,Campaign__r.From_Email__c,Campaign__r.From_Email_Id__c,Campaign__c,Email_Template_Id__c,
                                                                    Follow_Up_Days__c,Follow_Up_Time__c
                                                                FROM Campaign_Follow_Up_Stage__c
                                                                WHERE Id=:fuStageId];
        if(objFollowUpStage != null){
            return objFollowUpStage.get(0);
        }
        return null;
    }

    public static void createListEmailRecipientSource(String listEmailId, String campgainId){
        ListEmailRecipientSource objLERS = new ListEmailRecipientSource(
                ListEmailId = listEmailId,
                SourceListId = campgainId,
                SourceType = 'IncludeList'
        );
        insert objLERS;
        //To DO Remove schedule per time in follow up object
        if(objLERS.Id != null && listEmailId != null){
            CampaignEmailUtility.schdeuleEmailList(listEmailId);
        }
    }

    public static void schdeuleEmailList(String listEmailId){
        ListEmail objListEmail = new ListEmail(
                Id = listEmailId,
                Status = 'Scheduled'
        );
        update objListEmail;
    }

    public static list<OrgWideEmailAddress> getAllOrgWideEmailAddress(){
        return [SELECT Id,Address,DisplayName,IsAllowAllProfiles from OrgWideEmailAddress];
    }
}
Test Class:- 
@isTest(seeAllData = true)
 Public class CampaignEmailUtility_test{
     static testmethod void CampaignEmailUtility_TestMethod(){
 
 Campaign objcmp =new Campaign();
 objcmp .Name='Test Campaign';
 objcmp .IsActive=true;
 objcmp .Type='Email';
 objcmp .Status='Planned';
 objcmp.From_Email_Id__c = 'awsqualitytech@gmail.com';
 insert objcmp;
 
 Campaign_Follow_Up_Stage__c objCmpFlStg = new Campaign_Follow_Up_Stage__c();
         objCmpFlStg.Name = 'Stage 1';
         objCmpFlStg.Campaign__c = objcmp.id;
         objCmpFlStg.Email_Template_Id__c = '00X1F000001UleG';
         objCmpFlStg.Follow_Up_Date__c = system.today();
         objCmpFlStg.Follow_Up_Days__c = 5; 
         //objCmpFlStg .Follow_Up_Time__c=17:30; 
         objCmpFlStg .Local_Schedule_Date_Time__c = System.Now();  
         //objCmpFlStg .Schedule_time__c
         objCmpFlStg.Send_To_Prospects__c = 'All';
         objCmpFlStg.Status__c = 'Planned';
         objCmpFlStg.Time_Zone__c = 'PST';
         insert objCmpFlStg; 
         
         Campaign_Follow_Up_Stage__c objCmpFlStg1 = new Campaign_Follow_Up_Stage__c();
         objCmpFlStg1 .Campaign__c = objcmp.id;
         objCmpFlStg1 .Email_Template_Id__c = '00X1F000001UleG';
         objCmpFlStg1 .Follow_Up_Date__c = system.today();
         objCmpFlStg1 .Follow_Up_Days__c = 5; 
         //objCmpFlStg .Follow_Up_Time__c=17:30; 
         objCmpFlStg1 .Local_Schedule_Date_Time__c = System.Now().addMinutes(3);  
         //objCmpFlStg .Schedule_time__c
         objCmpFlStg1 .Send_To_Prospects__c = 'All';
         objCmpFlStg1 .Status__c = 'Completed';
         objCmpFlStg1 .Time_Zone__c = 'PST';
         insert objCmpFlStg1 ; 
 

     //OrgWideEmailAddress    oWEA = [select Id,Address,DisplayName from OrgWideEmailAddress];
        OrgWideEmailAddress owEA = new OrgWideEmailAddress();
                owEA.Address = objcmp.From_Email_Id__c;
                owEA.DisplayName = objcmp.Name;
                    
     User usr = [Select id,Email from User where Id = :UserInfo.getUserId()];

     System.RunAs(usr)

     {

      EmailTemplate validEmailTemplate = new EmailTemplate();
        validEmailTemplate.isActive = true;
        validEmailTemplate.Name = 'name';
        validEmailTemplate.DeveloperName = 'Abhi';
        validEmailTemplate.TemplateType = 'text';
        validEmailTemplate.HtmlValue = 'text';
        validEmailTemplate.Subject = 'name';
        validEmailTemplate.Body= 'Abhi';
        validEmailTemplate.FolderId = UserInfo.getUserId();
        
        insert validEmailTemplate;   
        
        list<EmailTemplate> objEmailTemplates = [SELECT Body,BrandTemplateId,Description,DeveloperName,Encoding,
                                                    EnhancedLetterheadId,FolderId,FolderName,HtmlValue,Id,
                                                    Markup,Name,NamespacePrefix,OwnerId,RelatedEntityType,Subject,
                                                    TemplateStyle,TemplateType,TimesUsed,UiType
                                                FROM EmailTemplate WHERE Id=:validEmailTemplate.ID LIMIT 1];
   // insert validEmailTemplate;
        
        ListEmail objLeadEmail = new ListEmail(
                Status='draft',
                CampaignId = objCmpFlStg.Campaign__c,
                FromAddress = oWEA.Address,
                FromName = 'Chris Taylor',
                HtmlBody = objEmailTemplates[0].HtmlValue,
                Name = objEmailTemplates[0].Subject,
                Subject = objEmailTemplates[0].Subject,
                TextBody = objEmailTemplates[0].Body);
                insert objLeadEmail;
                
                
   Test.startTest();     
 CampaignEmailUtility cEU = new CampaignEmailUtility();
 CampaignEmailUtility.getFollowUpStage(objCmpFlStg.id);
 CampaignEmailUtility.getEmailTemplateById(validEmailTemplate.id);
 CampaignEmailUtility.createListEmailRecipientSource(objLeadEmail.id,objcmp.id);
 CampaignEmailUtility.createListEmail(objCmpFlStg.Id);
 //CampaignEmailUtility.schdeuleEmailList(objLeadEmail.id);
 CampaignEmailUtility.getAllOrgWideEmailAddress();

         Test.stopTest();

     }
        
    
  }
 }

Error :-
System.QueryException: List has no rows for assignment to SObject
Stack TraceClass.CampaignEmailUtility.getEmailById: line 27, column 1
Class.CampaignEmailUtility.createListEmail: line 9, column 1
Class.CampaignEmailUtility_test.CampaignEmailUtility_TestMethod: line 90, column 1
Can we use duplicate rule in trigger?
I have a requirement where I need to update contacts if duplicate contact gets created or added.
I have a requirement while creating contact if it already exists then it will update the existing ones.
For example we have 2 contacts which are duplicate and while creating new contact it shows us that already two contacts are there with same data. In that case newer one updates it info into the existing ones. I am trying it with trigger on contact.

trigger ContactDuplicateTrigger on Contact (before insert) {
   //private final Contact contact;
    
    // Initialize a list to hold any duplicate records
    private List<sObject> duplicateRecords;
    
    // Define variable that’s true if there are duplicate records
    public boolean hasDuplicateResult{get;set;}
    
    Profile userProfile = [SELECT Id FROM Profile WHERE Name='Sales User'];
    if(userProfile.Id = UserInfo.getProfileId())
    return;

    Contact cont = new Contact( FirstName= 'Robin', LastName='Singh',Email='pintub.sfdc@gmail.com' );
    Database.SaveResult saveResult = Database.insert(cont, false);
    if (!saveResult.isSuccess()) {
    for (Database.Error error : saveResult.getErrors()) {
     if (error instanceof Database.DuplicateError) {
         Database.DuplicateError duplicateError = (Database.DuplicateError)error;
         Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();

         ApexPages.Message errorMessage = new ApexPages.Message(
                            ApexPages.Severity.ERROR, 'Duplicate Error: ' + 
                            duplicateResult.getErrorMessage());
         ApexPages.addMessage(errorMessage);

         this.duplicateRecords = new List<sObject>();

         Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();

         Datacloud.MatchResult matchResult = matchResults[0];
         Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
         this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
     }
}
}
Can anyone help me with the duplicate contact usdate via trigger.
Code:-
trigger ContactDuplicateTrigger on Contact (before insert) {
   //private final Contact contact;
    
    // Initialize a list to hold any duplicate records
    private List<sObject> duplicateRecords;
    
    // Define variable that’s true if there are duplicate records
    public boolean hasDuplicateResult{get;set;}
   
    Contact cont = new Contact( FirstName= 'Robin', LastName='Singh',Email='pintub.sfdc+123@gmail.com' );
    Database.SaveResult saveResult = Database.insert(cont, false);
    if (!saveResult.isSuccess()) {
    for (Database.Error error : saveResult.getErrors()) {
     if (error instanceof Database.DuplicateError) {
         Database.DuplicateError duplicateError = (Database.DuplicateError)error;
         Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();

         ApexPages.Message errorMessage = new ApexPages.Message(
                            ApexPages.Severity.ERROR, 'Duplicate Error: ' + 
                            duplicateResult.getErrorMessage());
         ApexPages.addMessage(errorMessage);

         this.duplicateRecords = new List<sObject>();

         Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();

         Datacloud.MatchResult matchResult = matchResults[0];
         Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
         this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
     }
}
}
}
public with sharing class CancelMembership_ctrl {
    @AuraEnabled
    public Static Account cancelMembership(String accountId){
        try {
            Account objAccount = [SELECT Id,Membership_Level__c,Membership_Type__c,Home_Clinic__c,
                                    Patient_Type__c,Membership_Add_On__c,
                                    Member_Status__c,Cancellation_Date__c, Signature_Date__c
                                    FROM Account
                                    WHERE Id = :accountId LIMIT 1];
            objAccount.Cancelled_membership__c = true;
            objAccount.Patient_Type__c = 'Registered';
            objAccount.Membership_Type__c = null;
            objAccount.Membership_Level__c = null;
            objAccount.Membership_Add_On__c = null;
            objAccount.Member_Status__c = 'Membership Cancelled';
            objAccount.Cancellation_Date__c = system.Today();
            update objAccount;
            return objAccount;
        }catch(Exception e){
            throw e;
        }
    }
    @AuraEnabled 
    public static List < String > getPicklistValue() {
        List < String > options = new List < String > ();
        Schema.DescribeFieldResult fieldResult = Account.Cancellation_Reason__c.getDescribe();
        List < Schema.PicklistEntry > ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f: ple) {
            options.add(f.getLabel());
        }
        return options;
    }
}
Need help with test class for @invocablemethod
Apex Class:-
public class SurveyResponseUpdate{
    
    @InvocableMethod
    public static void updateContactWithResponse(List<Id> ResId){
        set<Id> ConId = new set<Id>();
        set<Id> UserId = new set<Id>();
        map<Id, String> contactMap = new map<Id, String>();
        for(SurveyQuestionResponse surveyRes:[SELECT id, QuestionId, ResponseId, Response.SubmitterId, 
                                              QuestionChoiceId, Question.Name, QuestionChoice.Name
                                              FROM SurveyQuestionResponse
                                              WHERE Id =: ResId])
        {
            if(surveyRes.Response.SubmitterId != null 
               && string.valueOf(surveyRes.Response.SubmitterId).startswith('003')
               && surveyRes.Question.Name == 'How many employees are in your organization?')
            {
                contactMap.put(surveyRes.Response.SubmitterId, surveyRes.QuestionChoice.Name);
            }
        }
        
        List<Account> acclisttoUpdate = new List<Account>();
        
        for(Contact con:[SELECT Id, AccountId FROM Contact WHERE Id IN :contactMap.keyset() AND AccountId != NULL])
        {
            acclisttoUpdate.add(new Account(id = con.accountid, Number_of_Employees__c = contactMap.get(con.Id)));
        }
        
        if(acclisttoUpdate.size() > 0){
            update acclisttoUpdate;
        }
    }
}

Test Class:-
@isTest
private class Test_SurveyResponseUpdate {
    private static testMethod void doTest() {
        
        Account testAccount = new Account();
        testAccount.Name='Test Account' ;
        insert testAccount;
        
        List<Account> listAccount = new List<Account>();
        update listAccount;
         
        Contact cont = new Contact();
        cont.FirstName='Test';
        cont.LastName='Test';
        cont.Accountid= testAccount.id;
        insert cont;
        
        List<Contact> listCont = new List<Contact>();
        
        SurveyQuestion survQuestion = new SurveyQuestion();
        
        SurveyResponse survResponse = new SurveyResponse();
                
        SurveyQuestionChoice survQuestChoice = new SurveyQuestionChoice();
        
        Test.startTest();
            List<SurveyQuestionResponse> survQuestResponse = new List<SurveyQuestionResponse>();
            List<id> listId= new List<id>();
            SurveyResponseUpdate.updateContactWithResponse(listId);
        Test.stopTest();

        
    }
}

I am getting 52% coverage. 
Can anyone help me with the duplicate contact usdate via trigger.
Code:-
trigger ContactDuplicateTrigger on Contact (before insert) {
   //private final Contact contact;
    
    // Initialize a list to hold any duplicate records
    private List<sObject> duplicateRecords;
    
    // Define variable that’s true if there are duplicate records
    public boolean hasDuplicateResult{get;set;}
   
    Contact cont = new Contact( FirstName= 'Robin', LastName='Singh',Email='pintub.sfdc+123@gmail.com' );
    Database.SaveResult saveResult = Database.insert(cont, false);
    if (!saveResult.isSuccess()) {
    for (Database.Error error : saveResult.getErrors()) {
     if (error instanceof Database.DuplicateError) {
         Database.DuplicateError duplicateError = (Database.DuplicateError)error;
         Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();

         ApexPages.Message errorMessage = new ApexPages.Message(
                            ApexPages.Severity.ERROR, 'Duplicate Error: ' + 
                            duplicateResult.getErrorMessage());
         ApexPages.addMessage(errorMessage);

         this.duplicateRecords = new List<sObject>();

         Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();

         Datacloud.MatchResult matchResult = matchResults[0];
         Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
         this.hasDuplicateResult = !this.duplicateRecords.isEmpty();
     }
}
}
}
public with sharing class CancelMembership_ctrl {
    @AuraEnabled
    public Static Account cancelMembership(String accountId){
        try {
            Account objAccount = [SELECT Id,Membership_Level__c,Membership_Type__c,Home_Clinic__c,
                                    Patient_Type__c,Membership_Add_On__c,
                                    Member_Status__c,Cancellation_Date__c, Signature_Date__c
                                    FROM Account
                                    WHERE Id = :accountId LIMIT 1];
            objAccount.Cancelled_membership__c = true;
            objAccount.Patient_Type__c = 'Registered';
            objAccount.Membership_Type__c = null;
            objAccount.Membership_Level__c = null;
            objAccount.Membership_Add_On__c = null;
            objAccount.Member_Status__c = 'Membership Cancelled';
            objAccount.Cancellation_Date__c = system.Today();
            update objAccount;
            return objAccount;
        }catch(Exception e){
            throw e;
        }
    }
    @AuraEnabled 
    public static List < String > getPicklistValue() {
        List < String > options = new List < String > ();
        Schema.DescribeFieldResult fieldResult = Account.Cancellation_Reason__c.getDescribe();
        List < Schema.PicklistEntry > ple = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry f: ple) {
            options.add(f.getLabel());
        }
        return options;
    }
}