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
pooja chauchanpooja chauchan 

Missing ParentId in Test Class

Hi All,
We created a trigger for Chatter. When a post contains keyword ”legal', a new record under ChatterPost will be generated. We also created Test class but got error, please help, thank you so much.

Error Message System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ParentId]: [ParentId]
Stack Trace Class.ChatterPostTest.insertNewChatterPostTest: line 9, column 1


@isTest
public class ChatterPostTest
{
    static testMethod void insertNewChatterPostTest()
    {
        Test.StartTest();
        FeedItem f = new FeedItem();
        f.Body = 'legal test';
        insert f;
        Test.StopTest();
        System.assertEquals ('legal test', f.body);
    }
}

TRIGGER:
Trigger ChatterKeywordLegal on FeedItem (after insert) {
    List<FeedItem> FeedItems = new List<FeedItem>();
   for (FeedItem f : Trigger.new) {
           if (f.body!=null &&   f.body.contains('legal' ) ) {
               ChatterPost__c C = new ChatterPost__c();
               c.Description__c = f.body;
                   
              insert C;
        }
    }
   }
Best Answer chosen by pooja chauchan
Gaurav NirwalGaurav Nirwal

When creating a feed, you either need to connect it to an object, or a user. Updating parentID with userId should work, and the error of parentId not found should go away. Try this: 


view source
print?01 @isTest
public class ChatterPostTest
{
static testMethod void insertNewChatterPostTest()
  {
 Test.StartTest();
 FeedItem f = new FeedItem();
 f.Body = 'legal test';
 f.parentID = UserInfo.getUserId();
 insert f;
 Test.StopTest();
 System.assertEquals ('legal test', f.body);
  }
}