How to create the case with an attachment and topics using Test class?

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 :{

        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 });     


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 :
    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 :
    List<Attachment> relatedAttachments = attachments.get(record.Id);
    if (relatedAttachments != null)
        // add attachments an email
    // add email to collection
// send emails

Method 2

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(,....<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];
    System.assertEquals(1, attachments.size());

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

Method 3

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;


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x