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 : Trigger.new){

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

        mail.setBccSender(false);
        mail.setUseSignature(false);
        mail.setTargetObjectId(casevar.Id);
        mail.setTemplateId('XXXXXXXXX');
        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();
        efa.setFileName(a.Name);
        efa.setBody(a.Body);
        fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);
      //Send email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     
    }
}

Answers:

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 : trigger.new)
{
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    // set attributes
    emails.add(email);
}
Messaging.sendEmail(emails);

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>());
    attachments.get(record.ParentId).add(record);
}

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

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(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');
    attach.body=bodyBlob;
    // assign the case as the parent
    attach.parentId=c.id;
    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.

Method 3

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

Test.startTest();
    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() {
        Test.startTest();
        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;

        Test.stopTest();
    }


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x