I want to create a case which has an attachment, Billing Account, and topics. Given below is the code from my Test Class:

Scenario: Once user submit the case request and ask for approval. The request goes to the Manager for approval, once the request approves, an email goes to Legal team with an Case attachments in an email.

Topic__c tc = new Topic__c(Name ='My New topic');
Attachment att = new Attachment(Name = 'sample.pdf');

Case c = new Case(Origin = 'Phone',
                          Subject = 'New Testing',
                          Department__c = 'XXXXXXX', Priority = 'Normal',
                          Topic__c = tc.Id,
                          Risk_Approval__c = true);
insert c;

I am getting the below error:

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CaseTrigger: execution of BeforeInsert

My Trigger class:

trigger sendEAttachmentsInMail on Case (before insert, before update){

for(Case casevar : Trigger.new){

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.saveAsActivity = false;

      //Set email file attachments
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :casevar.Id])
        // Add to attachment file list
        Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
      //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     
  • Can you post your before insert trigger code or at least describe what it does? May 3, 2017 at 14:20
  • @Renato - Please see the updates above. May 3, 2017 at 16:28
  • 1
    You are using Topic__c = tc.Id in your case object, but you have not inserted the Topic record itself. Is the the complete test class code ? if yes, thats the problem.
    – Mahmood
    May 3, 2017 at 16:46
  • 1
    It seems like there should be more to that error message. Is that the whole thing?
    – Adrian Larson
    May 3, 2017 at 16:47
  • 1
    I know, right? it seems odd? Either the test class is incomplete or well ... the error is he hasn't inserted topic__c and attachment before insertion of case.
    – Mahmood
    May 3, 2017 at 16:50

3 Answers 3


One thing you should fix is to bulkify your sendEmail call. You only get 10 invocations per transaction, so even inserting 11 Case records will hit a LimitException. You also have a query you need to bulkify (on Attachment).

Email Bulkification

List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
for (Case record : trigger.new)
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    // set attributes

Query Bulkification

Map<Id, List<Attachment>> attachments = new Map<Id, List<Attachment>>();
for (Attachment record : [
    SELECT Name, Body FROM Attachment
    WHERE ParentId IN :trigger.newMap.keySet()
    if (!attachments.containsKey(record.ParentId))
        attachments.put(record.ParentId, new List<Attachment>());

for (Case record : trigger.new)
    List<Attachment> relatedAttachments = attachments.get(record.Id);
    if (relatedAttachments != null)
        // add attachments an email
    // add email to collection
// send emails

Suggested test class to insert Case with Attachment and your custom object:

    // insert Topic__c obj fields 
    Topic__c topic = new Topic__c(); 
    insert topic;
    Case c=new Case(Topic__c=topic.id,....<other fields and values>);
    insert c;

    // attachment insert
    Attachment attach=new Attachment();     
    attach.Name='Unit Test Attachment';
    Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
    // assign the case as the parent
    insert attach;

    List<Attachment> attachments=[select id, name from Attachment where parent.id=:cse.id];
    System.assertEquals(1, attachments.size());

There is a good article related to attachment insertion in test classes, I suggest you go through that.


Ok. I was able to test my trigger logic like below. Giving me 100% code coverage.

    public static Account acc = null;
    static Id id = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();

    public static Blob createAttachmentBody(){
        String body = 'XXXXXXXXXXXXX';
        return Blob.valueof(body);

    private static testMethod void testRiskCaseApproval() {
        Topic__c tc = new Topic__c(Name ='Risk Management');   

        acc = new Account(FirstName = 'FirstName', LastName='LastName', recordTypeId = id);
        insert acc;

        Account a = [select PersonContactId from Account where Id = :acc.Id];

        // Risk Approved Case
        Case c = new Case(Origin = 'Phone', Subject = 'XXXXXXXXXXXXX', Risk_Approval__c = true,
                          Department__c = 'XXXXXXXXXXXX', Priority = 'Normal',
                          Topic__c = tc.Id, AccountId = acc.Id, ContactId = a.PersonContactId);
        insert c;

        Attachment att = new Attachment(Name = 'XXXXXXXX', Body = Blob.valueof('XXXXXXXXXXXXXX'), ParentId = c.Id);
        insert att;


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .