+ Start a Discussion
Sanjat Samal 8Sanjat Samal 8 

How do I write test class for my below code.

Public class EmailMessageDelete{
    public static void preventDeletionEmailMessage(EmailMessage [] pEmailMessage, EmailMessage [] pOldEmailMessage) {

        //EmailMessage deletion is only allowed for administrator
        Set<String> UserNames = new Set<String>();
        for(Exception_Users_List__c ListUsers : [Select Name,    Emp_ID__c from Exception_Users_List__c])
{
                UserNames.add(ListUsers.Emp_ID__c);
}

        String Names=[Select id,EmployeeNumber from User].EmployeeNumber;
        for(EmailMessage currentEmailMessage : pOldEmailMessage) {
            
            //Check if current user is not a system administrator
            if(UserNames.contains(Names)){
                currentEmailMessage.addError(System.Label.Custom_Label_for_email_object);
            }
        }
    }
}
Raj VakatiRaj Vakati
Try this code add other required fields
@isTest
public class EmailMessageDeleteTest {

 @isTest static void testGetter() {
    
    EmailMessageDelete pdc = new EmailMessageDelete();
System.Test.startTest() ;
 // Setup test data
        // Create a unique UserName
        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'standt', Email='standarduser@testaskdkgasdorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,EmployeeNumber='787878',
        TimeZoneSidKey='America/Los_Angeles',
         UserName=uniqueUserName);

        System.runAs(u) {
 
  //Insert test case record
        Case c = new Case();
        c.Subject = 'Om Test';  
        c.Description_HTML__c = 'testing';
        Status ='New';
        Priority = 'Medium';
        Origin = 'Email';
        insert c;

        //Insert emailmessage for case
        EmailMessage email = new EmailMessage();
        email.FromAddress = 'test@abc.org';
        email.Incoming = True;
        email.ToAddress= 'test@xyz.org';
        email.Subject = 'Test email';
        email.HtmlBody = 'Test email body';
        email.ParentId = c.Id; 
        insert email;
		
		Exception_Users_List__c  ins = new Exception_Users_List__c () ;
		ins.Name ='787878';
		insert ins ;
		
		
		EmailMessageDelete.preventDeletionEmailMessage(new List<EmailMessage>{email} , new List<EmailMessage>{email});
		}
System.Test.stopTest() ;

 }
}