+ Start a Discussion
John ClevelandJohn Cleveland 

Help with Test Class - System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, NewCaseEmail: execution of AfterInsert caused by: System.EmailException: SendEmail failed.

I had a previous post but found an issue with that and now hitting another error after I've changed my code up.  I've included my trigger and test class below, but I am not able to get around the error below.  I also can not get a few lines covered with my class.  Any help is greatly appreciated.
 
Error MessageSystem.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, NewCaseEmail: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: null: [toAddresses, null]

Trigger.NewCaseEmail: line 77, column 1: []
Stack TraceClass.TestNewCaseEmailTrigger.testNewCase: line 23, column 1

I am using an actual email in the trigger though.
 
I am unable to get lines 44-51 and lines 66-71 covered with my test class.  

One thing to note is that I have a workflow rule with evaluation criteria of "Evaluate the rule when a record is created, and every time it's edited" and part of the criteria is status is New, so it's running on the cases created from this.  That's why I added lines 49-51 thinking it would help cover after the validation rule fired.

Apex Trigger: 
trigger  NewCaseEmail on Case (after insert,after update) {

for(Case t : trigger.new){
// Criteria for record type
 Id RecTypeId =  [Select Id, Name from RecordType where name = 'Test Record Type' limit 1].Id;

    if (t.Status == 'New' && t.Field_2__c  == 0 && t.RecordTypeId == RecTypeId ){
// New Email
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Setting the from to the OrgWideEmailAddress for Shared Inbox
    OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'test@test.com'];    //Looking for ID for Email Address
    if ( owea.size() > 0 ) {
       email.setOrgWideEmailAddressId(owea.get(0).Id);    //Setting email from address to the ID of the Inbox
    } 

      Case cse = [SELECT id,  Case.owner.Name, Case.owner.Email,  Status, CaseNumber, Field_1__c , Field_2__c from Case WHERE Id = :t.Id];                    


        // create email content
        String CaseId = cse.id; 
        
        CaseId = CaseId.substring(0,CaseId.length()-3);
        
        String subject = 'Test Subject: ' + Cse.Field_2__c + '- Case #: ' + Cse.CaseNumber; 
        email.setSubject(subject);


        String line1 = 'Line 1. ' + '\n\n';
        String line2 = 'Line 2: ' +  cse.owner.Name + '\n';
        String line3 = 'Line 3: '+ Cse.Field_1__c  + '\n'; 
        String line4 = 'Line 4: '+ Cse.Field_2__c + '\n'; 
        
        
        
        String body = line1 + line2 + line3 + line4;
        email.setPlainTextBody(body);
        
       
        //Put your record id in ParentId
List<Attachment> attList = [SELECT id, Name, body, ContentType FROM Attachment WHERE ParentId = : CaseId];
// List of attachments handler
Messaging.EmailFileAttachment[] efaList = new List<Messaging.EmailFileAttachment>();
for(Attachment att : attList)
{ // Create the email attachment 
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(att.Name);
efa.setBody(att.body);
efa.setContentType(att.ContentType);
efa.setInline(false);
efaList.add(efa);
 }
// Attach files to email instance
email.setFileAttachments(efaList);

email.setPlainTextBody(body);

Id caseTeamRoleId= [SELECT Id FROM CaseTeamRole WHERE Name = 'Test Role' LIMIT 1].id;

List<CaseTeamMember> catmlst = [select Id, MemberId from CaseTeamMember where TeamRoleId = :caseTeamRoleId and ParentId = :t.Id];

String [] toEmails = new List<String>();

toEmails.add(cse.owner.Email);

for(CaseTeamMember ctm : catmlst)
{   
    String teamMemId = ctm.MemberId;
    teamMemId = teamMemId.substring(0, teamMemId.length()-3);  
    String userEmailId = [select Id, Email from User where Id = :teamMemId].Email;   
    toEmails.add(userEmailId);
}    


   
        email.setToAddresses(toEmails);
        if(email != null){
            Messaging.sendEmail(new Messaging.singleEmailMessage[] {email});
                           
          }
          
    
}
}

}

Test Class:
@isTest(seeAllData=true)
private class TestNewCaseEmailTrigger  {

    
    public static Case newCse;
    
   
    static void init(){
    
    newCse = new Case();

    newCse.Status = 'New';
    newCse.Field_2__c = 0;
    newCse.RecordTypeID = [select ID from RecordType where Name = 'Test Record Type' and sObjectType = 'Case'].ID;
    newCse.OwnerId= [select ID from Group where Name = 'Queue1' and Type = 'Queue'].ID;


    }

    static testMethod void testNewCase() {
    init();
    Test.startTest();
    insert newCse;    
        
    Case cse = [select Id, Field_2__c from Case where Id = :newCse.id];
    cse.Field_2__c  = 1;
    update cse;
        
    Attachment attach=new Attachment(); 
    attach.Name='Test Attachment'; 
    Blob bodyBlob=Blob.valueOf('Test Attachment Body'); 
    attach.body=bodyBlob; attach.parentId=newCse.Id;
    insert attach;
        
        Id userId = [SELECT Id FROM User WHERE IsActive = true AND Profile.Name = 'System Administrator' LIMIT 1].id;
  
   
        Id caseTeamRoleId= [SELECT Id FROM CaseTeamRole WHERE Name = 'Test Role' LIMIT 1].id;
        List<CaseTeamMember> catmList=new List<CaseTeamMember>();
        
        CaseTeamMember tm=new CaseTeamMember();
        tm.ParentId=newCse.Id;
        tm.MemberId=userId;
        tm.TeamRoleId =caseTeamRoleId;
        catmList.add(tm);
        
        upsert catmList;
        
    cse.Status = 'Pending';
    cse.OwnerId = 'newCse.OwnerId';
    update newCse;
        
        
    Case cse2 = [select Id, Field_2__c  from Case where Id = :newCse.id];
    cse2.Field_2__c  = 0;
    update cse2;
                
    Test.stopTest();
    }
   

}

 
LBKLBK
Do you need line 68 in your code?
teamMemId = teamMemId.substring(0, teamMemId.length()-3);
Ideally, it should work without this line.
Also, can you add a System.debug on teamMemId and userEmailId to make sure you get the right data here?

 
John ClevelandJohn Cleveland
After I took that line out, it still isn't covering the other lines.

I have debug to return efa list from the for loop at line 43 and nothing is being returned.  I also have debug after line 59 to return what's grabbed there but nothing is returned rows are 0.  I'm pretty sure this is why the lines I mentioned aren't covered with the class but I can't figure out why nothing is returned in those queries.  That is what I need help finding.
John ClevelandJohn Cleveland
I'm still having issues with this.  Any help would be greatly appreciated.