+ Start a Discussion
Sean ClarkSean Clark 

Creating a Test Class of an Apex Trigger

Hello,

I am trying to write a test class for the below Apex Trigger but could do with some assistance as this is a first for me.

Could anyone help?

​-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Trigger OldMVPTrigger on MVP__c (after update) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30) && system.today() <=    system.today().toStartOfWeek().addDays(5) ) 
        {
           task t = new Task();
           t.Subject = 'You need to call '+mvp.MVP_Forename__c+' today';
           t.ownerId = mvp.MVP_Owner__c;
           t.WhatId = mvp.Id;
           t.ActivityDate = mvp.Last_Contacted_On__c;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Best Answer chosen by Sean Clark
devedeve
@isTest 
private class OldMVPTrigger {
    
@isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
        testmvp.MVP_Owner__c = UserInfo.getUserId();
       insert testmvp;
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        
        Test.startTest();
            update testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}

All Answers

devedeve
Hi sean,

Please try this:

@isTest 
private class OldMVPTrigger {

    @isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        
        Test.startTest();
            insert testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
Sean ClarkSean Clark
Hello Deve,

Thank you for this, i have run the test and....

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [MVP__c]: [MVP__c]

Class.OldMVPTrigger.testInsert: line 9, column 1
devedeve
Hi Sean,

Can you please provide required fields for MVP__c object
Sean ClarkSean Clark
The only requried field is the MVP:

FIELD LABEL              FIELD NAME             DATA TYPE

MVP                             MVP__c                     Master-Detail(Contact)
devedeve
@isTest 
private class OldMVPTrigger {

    @isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact(name='testContact', LastName='test');
        insert testContact;
        testmvp.MVP__c = testContact;
        
        Test.startTest();
            insert testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
Sean ClarkSean Clark
There were a few problems which i amended which is the below. 

The test still failed due to: 

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [MVP__c]: [MVP__c]

Class.OldMVPTrigger.testInsert: line 14, column 1
-------------------------------------------------------------------------------------------------------------------------------------------------
@isTest 
private class OldMVPTrigger {

    @isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Name;
        
        Test.startTest();
            insert testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
-------------------------------------------------------------------------------------------------------------------------------------------------
devedeve
Try this :-

@isTest 
private class OldMVPTrigger {

    @isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
        
        Test.startTest();
            insert testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
Sean ClarkSean Clark
Really appriciate the help on this!

The test has failed again but with a different Error & StackTrace:

ERROR =                       System.QueryException: List has no rows for assignment to SObject

Stack Trace=                  Class.OldMVPTrigger.testInsert: line 17, column 1

 
devedeve
Yes this is because 'system.today() <=    system.today().toStartOfWeek().addDays(5)' condition is false so it does not goes inside if and do not create task record.
Sean ClarkSean Clark
What does this mean? 

'system.today() <=    system.today().toStartOfWeek().addDays(5)' was added so that if it was Saturday or Sunday, the task record would create on the monday.
devedeve
Yes. Can you please check debug what the date it returning using 'system.today().toStartOfWeek().addDays(5)'.

Trigger OldMVPTrigger on MVP__c (after update) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
System.debug('date='+system.today().toStartOfWeek().addDays(5));
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30) && system.today() <=    system.today().toStartOfWeek().addDays(5) ) 
        {
           task t = new Task();
           t.Subject = 'You need to call '+mvp.MVP_Forename__c+' today';
           t.ownerId = mvp.MVP_Owner__c;
           t.WhatId = mvp.Id;
           t.ActivityDate = mvp.Last_Contacted_On__c;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}

now run test class check date value
Sean ClarkSean Clark
Where do i check the debug? 

Also where do i use the trigger you provided?
Sean ClarkSean Clark

I'm not 100% on what you mean, this is my first Test Class.

Would you be able to describe what i need to do? 

Thank you!

Sean ClarkSean Clark
Is this what you were looking for? 

14:20:45:002 USER_DEBUG [1]|DEBUG|date=2018-08-18 00:00:00
devedeve
Yes it's giving tomorrow's date that's not equivalent to today's date with which you are comparing so this is the reason why testclass is failing.
Sean ClarkSean Clark
Okay, would you have a suggestion on how to amend this? 
devedeve
Ya.. you can add 4 days instead of 5 in this 'system.today().toStartOfWeek().addDays(4) '
Sean ClarkSean Clark
Okay great, i've done this and is now returning today's date! 

Although the test class is still failing?

Apex Trigger
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Trigger OldMVPTrigger on MVP__c (after update) {
    
    List<Task> taskListToInsert = new List<task>();
    
    for(MVP__c mvp:Trigger.new)
    {
        if(mvp.Last_Contacted_On__c == Date.Today().addDays(-30) && system.today() <=    system.today().toStartOfWeek().addDays(4) ) 
        {
           task t = new Task();
           t.Subject = 'You need to call '+mvp.MVP_Forename__c+' today';
           t.ownerId = mvp.MVP_Owner__c;
           t.WhatId = mvp.Id;
           t.ActivityDate = mvp.Last_Contacted_On__c;
           taskListToInsert.add(t);
        }
    }
    if(taskListToInsert.size() > 0)
    {
        insert taskListToInsert;
    }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Apex Test Class
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@isTest 
private class OldMVPTrigger {

    @isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
        
        Test.startTest();
            insert testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
devedeve
I have done some mistake please try now:-

@isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
       insert testmvp;
       testmvp.name = 'new';
        
        Test.startTest();
            update testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
Sean ClarkSean Clark
The below is now coming up with: Field is not writeable: MVP__c.Name.

This is for Line 13 - (testmvp.name = 'new';)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@isTest 
private class OldMVPTrigger {
    
@isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
       insert testmvp;
       testmvp.name = 'new';
        
        Test.startTest();
            update testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
devedeve
@isTest 
private class OldMVPTrigger {
    
@isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
       insert testmvp;
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        
        Test.startTest();
            update testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
Sean ClarkSean Clark
This now works, i have rerun the test and its failed due to:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
System.DmlException: Update failed. First exception on row 0 with id a2B1w0000008UdZEAU; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OldMVPTrigger: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Assigned To ID: owner cannot be blank: [OwnerId]

Trigger.OldMVPTrigger: line 19, column 1: []

Class.OldMVPTrigger.testInsert: line 15, column 1
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Although the overall code coverage of the OldMVPTrigger is: 100% - 12/12
Sean ClarkSean Clark
The below is now coming up with: Field is not writeable: MVP__c.Name.

This is for Line 14 - (testmvp.name = 'new';)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@isTest 
private class OldMVPTrigger {
    
@isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
        testmvp.MVP_Owner__c = UserInfo.getUserId();
       insert testmvp;
       testmvp.name = 'new';
        
        Test.startTest();
            update testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
devedeve
@isTest 
private class OldMVPTrigger {
    
@isTest static void testInsert() {
        MVP__c testmvp = new MVP__c();
        Contact testContact = new Contact();
        testcontact.FirstName = 'testcontact';
        testcontact.LastName = 'test';
        insert testContact;
        testmvp.MVP__c = testContact.Id;
        testmvp.MVP_Owner__c = UserInfo.getUserId();
       insert testmvp;
        testmvp.Last_Contacted_On__c = Date.Today().addDays(-30); 
        
        Test.startTest();
            update testmvp;
        Test.stopTest();
        
        Task task = [select id from task limit 1];
        System.assertNotEquals(null, task.Id, 'Id should not be null');
    }
}
This was selected as the best answer
Sean ClarkSean Clark
Great!! It work, thank you for your help! Absolute hero.

What was going wrong with the test?