function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
oenoen 

How to write a testMethod for feeditem trigger

Hi everyone,

 

I need help write a testMethod for my trigger, can anyone help please? Below is a trigger that works in the SandBox, but when i deploy it in production i get a '

Test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required'

 

----Trigger----

trigger EmailonPost on FeedItem (after insert) {

for (FeedItem f: trigger.new) {
        Id myparentId = f.parentId;
Id myCreatedUser = f.createdbyid;
Milestone1_Milestone__c myMile =  [SELECT id,Name FROM Milestone1_Milestone__c WHERE id =:myparentId]; 
String myMileName = myMile.Name;

User myCreateUser =  [SELECT id,Name FROM User WHERE id =:myCreatedUser]; 
String CreatedName = myCreateUser.Name;

String myPostbody = f.body;

  List<EntitySubscription> newEN = [SELECT id,Parentid,subscriberid FROM EntitySubscription WHERE Parentid =:myparentId]; 
         
          for(EntitySubscription a : newEN){
         id Iduser =a.subscriberid;
        try{

List<Messaging.SingleEmailMessage> email = new List<Messaging.SingleEmailMessage>();  
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   //mail.setToAddresses(new String[] {'klin@evolvediscovery.com'});          
       mail.setTargetObjectId(Iduser);
       // mail.setTemplateID(template.ID);
        mail.setSaveAsActivity(false);
   mail.setSubject('New post on Milestone: ' + myMileName);  
    mail.setPlainTextBody(CreatedName + ' wrote: ' + ' \r\n' + ' \r\n' + myPostbody);
        //mail.setWhatId(c.ID);
        
        email.add(mail);
 Messaging.sendEmail(email);

       
        } catch (DmlException e) {}
          }

    }


}

 

 

What this trigger trying to do is send a email to all the follower that are currently following the custom object.

 

Below is my attempt to write a testMethod, i couldn't get it to work because i don't have a clue how the logic behind a test method.

 

---Apex Class---

@isTest
private class EmailonPostTester {

    static testMethod void myEmailonPostTest() {

FeedItem post = new FeedItem();

post.ParentId = '005G0000002hIbJIAU';
post.Body = 'Enter post text here';

test.StartTest();
insert post;
test.StopTest();

    }
}

I get this error when did a run test:

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

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.EmailonPost: line 6, column 1: []

Best Answer chosen by Admin (Salesforce Developers) 
Puja_mfsiPuja_mfsi

Hi,

Don't use query inside the for loop because it hits the salesforce governer limit. Always use the collections to avoid query inside for loop.And never perform any operation like sendEmail() inside for loop because there is a limitation of calling SendEmail() method.Never use hardcoded Ids in test class.

 

I have modified your code and write the test class.

 

/********************************* Trigger -Start **************************************/

trigger EmailonPost on FeedItem (after insert) {

Set<String> parentIdsSet = new Set<String>();
Set<String> createdUserIdsSet = new Set<String>();
Map<String,List<EntitySubscription>> entitySubMap = new Map<String,List<EntitySubscription>>();
List<Messaging.SingleEmailMessage> email = new List<Messaging.SingleEmailMessage>();
String nspKeyPrefix = Milestone1_Milestone__c.sObjectType.getDescribe().getKeyPrefix();

for (FeedItem f: trigger.new) {
String parentid = f.Parentid;
if( parentid.substring(0,3) == nspKeyPrefix ) {
parentIdsSet.add( f.Parentid );
createdUserIdsSet.add( f.createdById );
}
}
Map<Id,Milestone1_Milestone__c> oppMap = new Map<Id,Milestone1_Milestone__c>([Select Id,Name from Milestone1_Milestone__c where id in :parentIdsSet]);
Map<Id,User> userMap = new Map<Id,User>([Select Id,name from User where id in :createdUserIdsSet]);

for( EntitySubscription es : [select id,ParentId,subscriberid from EntitySubscription where Parentid =:parentIdsSet] )
{
List<EntitySubscription> entityList = new List<EntitySubscription>();
if( entitySubMap.containsKey(es.ParentId) ) {
entityList = entitySubMap.get( es.ParentId );
}
entityList.add( es );
entitySubMap.put( es.ParentId,entityList );
}

for (FeedItem f: trigger.new) {
if( entitySubMap.containsKey( f.Parentid ) ) {
for( EntitySubscription es : entitySubMap.get( f.Parentid )) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(es.subscriberId);
mail.setSaveAsActivity(false);
mail.setSubject('New post on Milestone1_Milestone__c: ' + oppMap.get(f.ParentId).Name);
mail.setPlainTextBody(userMap.get(f.createdById).Name + ' wrote: ' + ' \r\n' + ' \r\n' + f.body);
email.add(mail);
}
}
}

if(email != null ) {
Messaging.sendEmail(email);
}
}

/***************************************** Trigger - End ****************************************/

 

 

/**************************************** Test Class - START ****************************************/

@isTest(seeAlldata = true )
private class EmailonPostTester {
static testMethod void unitTest() {
Milestone1_Milestone__c mile = new Milestone1_Milestone__c (
Name = 'test',
/** Mandatory fields of this object.**/
);
insert mile;

Profile p = [select id from profile where Name = :'System Administrator' limit 1];
User pu = new User(profileId = p.id, username = 'tt@ff.com', email = 'pp@cc.com',
emailencodingkey = 'UTF-8', localesidkey = 'en_US',
languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
alias='cspu', lastname='lastname');
insert pu;


EntitySubscription es = new EntitySubscription (
ParentId = mile.id,
SubscriberId = pu.Id
);
insert es;

FeedItem feed = new FeedItem (
ParentId = mile.id,
Body = 'Hello'
);
insert feed;
}
}

/****************************************** Test Class - END **********************************/

 

Please let me know if you have any issue regarding same.

If this post helps you then please give me Kudos by click on the start at left

All Answers

Puja_mfsiPuja_mfsi

Hi,

Don't use query inside the for loop because it hits the salesforce governer limit. Always use the collections to avoid query inside for loop.And never perform any operation like sendEmail() inside for loop because there is a limitation of calling SendEmail() method.Never use hardcoded Ids in test class.

 

I have modified your code and write the test class.

 

/********************************* Trigger -Start **************************************/

trigger EmailonPost on FeedItem (after insert) {

Set<String> parentIdsSet = new Set<String>();
Set<String> createdUserIdsSet = new Set<String>();
Map<String,List<EntitySubscription>> entitySubMap = new Map<String,List<EntitySubscription>>();
List<Messaging.SingleEmailMessage> email = new List<Messaging.SingleEmailMessage>();
String nspKeyPrefix = Milestone1_Milestone__c.sObjectType.getDescribe().getKeyPrefix();

for (FeedItem f: trigger.new) {
String parentid = f.Parentid;
if( parentid.substring(0,3) == nspKeyPrefix ) {
parentIdsSet.add( f.Parentid );
createdUserIdsSet.add( f.createdById );
}
}
Map<Id,Milestone1_Milestone__c> oppMap = new Map<Id,Milestone1_Milestone__c>([Select Id,Name from Milestone1_Milestone__c where id in :parentIdsSet]);
Map<Id,User> userMap = new Map<Id,User>([Select Id,name from User where id in :createdUserIdsSet]);

for( EntitySubscription es : [select id,ParentId,subscriberid from EntitySubscription where Parentid =:parentIdsSet] )
{
List<EntitySubscription> entityList = new List<EntitySubscription>();
if( entitySubMap.containsKey(es.ParentId) ) {
entityList = entitySubMap.get( es.ParentId );
}
entityList.add( es );
entitySubMap.put( es.ParentId,entityList );
}

for (FeedItem f: trigger.new) {
if( entitySubMap.containsKey( f.Parentid ) ) {
for( EntitySubscription es : entitySubMap.get( f.Parentid )) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(es.subscriberId);
mail.setSaveAsActivity(false);
mail.setSubject('New post on Milestone1_Milestone__c: ' + oppMap.get(f.ParentId).Name);
mail.setPlainTextBody(userMap.get(f.createdById).Name + ' wrote: ' + ' \r\n' + ' \r\n' + f.body);
email.add(mail);
}
}
}

if(email != null ) {
Messaging.sendEmail(email);
}
}

/***************************************** Trigger - End ****************************************/

 

 

/**************************************** Test Class - START ****************************************/

@isTest(seeAlldata = true )
private class EmailonPostTester {
static testMethod void unitTest() {
Milestone1_Milestone__c mile = new Milestone1_Milestone__c (
Name = 'test',
/** Mandatory fields of this object.**/
);
insert mile;

Profile p = [select id from profile where Name = :'System Administrator' limit 1];
User pu = new User(profileId = p.id, username = 'tt@ff.com', email = 'pp@cc.com',
emailencodingkey = 'UTF-8', localesidkey = 'en_US',
languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
alias='cspu', lastname='lastname');
insert pu;


EntitySubscription es = new EntitySubscription (
ParentId = mile.id,
SubscriberId = pu.Id
);
insert es;

FeedItem feed = new FeedItem (
ParentId = mile.id,
Body = 'Hello'
);
insert feed;
}
}

/****************************************** Test Class - END **********************************/

 

Please let me know if you have any issue regarding same.

If this post helps you then please give me Kudos by click on the start at left

This was selected as the best answer
oenoen

Thank you so much Puja for the complete revision of the code!! I learned alot from your code. You code helped me understand what testMethod is for and logic on Apex scritping.

 

Thank you so much!!