1

We created a trigger for Chatter. When a post contains the keyword "legal", a new record under ChatterPost will be generated. We also created a Test class but got error. Since we're rather new to trigger, don't know how to fix the test class, 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

Test

@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;
        }
    }
1

As the error states, you're missing a field. You need to specify a ParentId value before attempting to insert the FeedItem. That would go in your test method like so:

f.ParentId = UserInfo.getUserId(); // Associate to the current user
insert f;

You'll want to read more about FeedItem to see if there's any other fields you'll need to specify.

  • It works!! Thanks so much for the fast response and the helpful information. We thought about maybe should have user id for inserting feed, since we got no programming background don't know how to get user id. Btw, how do you come up with the code "UserInfo.getUserId()", is it a fixed pattern for getting user id? – user11377 Sep 18 '14 at 3:02
  • @user11377 This is in the Force.com Apex Code Developer's Guide. Learning the API (the various functions the system offers) will help greatly. In particular, I recommend learning UserInfo, System, Test, and the various data types (e.g. Integer, Date, DateTime) first. After that, you can dive into more advanced topics as you need them. – sfdcfox Sep 18 '14 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.