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
rebvijkumrebvijkum 

Test class for a simple trigger

The code coverage is still 0%, even though it is successfull. need some help plz
My Trigger:
trigger ArticleFeedbackAfterTrigger on Article_Feedback__c (after insert, after update) {
    List<FeedItem> lstFeeds = new List<FeedItem>();  
    for(Article_Feedback__c af : Trigger.new) {
        FeedItem fi = new FeedItem();
        fi.Type = 'TextPost';
        fi.Title= af.Name;
        fi.ParentId = af.Article_ID__c;
        fi.Body = af.Comments__c;
        fi.CreatedById=af.CreatedById;
        lstFeeds.add(fi);
    }
    if(lstFeeds.size() > 0) { insert lstFeeds; }
}
My Test Class:
@isTest
private class ArticleFeedbackTrigger_test {

    static testmethod void test_trigger(){
        Article_Feedback__c af =new Article_Feedback__c(Article_ID__c='kac236789045672000',Comments__c='Body for the feed');
        //insert af;
        List<FeedItem> lstFeeds = new List<FeedItem>();
        FeedItem fi = new FeedItem();
        fi.Type = 'TextPost';
        fi.Title= 'test article';
        //fi.ParentId = af.Article_ID__c;
        fi.Body = af.Comments__c;       
        //Name='test_article',,CreatedById='kac895643289456000'
        lstFeeds.add(fi);
        system.assertEquals(fi.Body ,'Body for the feed');
    }
}
Best Answer chosen by rebvijkum
pconpcon
That is because you have a hardcoded article Id that does not exist in your test.  You need to:
  1. Generate a new article object
  2. Insert it.
  3. Use the article's Id in your Article_Feedback__c object
When writing tests you should create all of the test data.  If your class is post API version 24 you do not have access to data created outside of the test class by default.

All Answers

Arthur LockremArthur Lockrem
Uncomment the insert statement.

insert af 
rebvijkumrebvijkum
I'm getting an error if i did that,

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

caused by: System.StringException: Invalid id: kac236789045672000

Trigger.ArticleFeedbackAfterTrigger: line 10, column 1: []
Stack Trace Class.ArticleFeedbackTrigger_test.test_trigger: line 7, column 1
pconpcon
That is because you have a hardcoded article Id that does not exist in your test.  You need to:
  1. Generate a new article object
  2. Insert it.
  3. Use the article's Id in your Article_Feedback__c object
When writing tests you should create all of the test data.  If your class is post API version 24 you do not have access to data created outside of the test class by default.
This was selected as the best answer