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
Nitzan MarinovNitzan Marinov 

Insert failed on trigger test

Hi everyone,

This may be really simple but I'm new to this so would appreciate any help.

I have this test trigger:

@isTest
private class TESTCLASS_EventTrigger {
static testMethod void validateEventTrigger() {

   datetime myDateTime =
   datetime.newInstance(2012, 1, 1);
   
Clients__c c = TestUtilities.insertClient();
Event e = new Event(Subject='Test Class Call', WhatID ='a0EC000000AkWqD',
                    DurationInMinutes=30, StartDateTime=myDateTime);
// Insert Client & Event
insert c;
insert e;

// Retrieve the new Event
e = [SELECT ID, Calendar_Title__c FROM Event WHERE Subject = 'Test Class Call'];
System.debug('Calendar_Title__c: ' + e.Calendar_Title__c);

// Test that the trigger correctly updated the price
System.assertEquals('Camilla Ferdinand: Test Class Call', e.Calendar_Title__c);
}
}

Here's the test utility:
@isTest
public with sharing class TestUtilities {
    
    public Contact      aContac         {get; set;}
    public Attachment   aAttachment     {get; set;}
    
    static User testUser;
    
    public void generateContact(){

        this.aContac                = new Contact();
        this.aContac.firstName      = 'Test';
        this.aContac.LastName       = 'Test';
        
        insert this.aContac;

        this.aAttachment = new Attachment();
        this.aAttachment.Body = Blob.valueOf('String');
    }
    
    public static TestUtilities generateTest(){
        TestUtilities e = new TestUtilities();
        e.generateContact();
        return e;
    }
    
        public static User createUser(Id profileId)
        {   
            //fetch existing users with provided profile and role
            List<User> userLst = [Select Id From User where ProfileId =: profileId and IsActive = :true Limit 1];
            
            User user;
            
            if(userLst.size()>0)
            {
                //at least one user exists; return user record
                user =  userLst[0];
            }
            else
            {
                //user does not exist; create new user
                user = new User(profileid = profileId,
                                alias = 'standt', email = 'standarduser@testorg.com',
                                emailencodingkey = 'UTF-8', lastname = 'Tsting', languagelocalekey = 'en_US',
                                localesidkey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                username = profileId + '@testorg.com');
                insert user;
            }
           
            return user;
        }
        
    public static Clients__c insertClient()
    {
        Clients__c c = new Clients__c(Name ='TestClient', Active__c = true,
                                      OC_Programme__c = 'OC Central', Current_Address__c = 'N/A',
                                      Primary_Phone_Number__c = 'N/A');
        return c;
    }
    
    public static Contact insertContact()
    {
        Contact c = new Contact(FirstName ='Test',LastName ='Test', Training_Contact__c = true);
        return c;
    }
    
    public static Project__c insertProject()
    {
        Profile p = [select id from profile where name='OC Impact'];
        UserRole r = [select id from UserRole where name='OC Impact Director'];
        User userSRO  = TestUtilities.createUser(p.Id);
        RecordType rt = [select id from RecordType where SobjectType = 'Project__c' and DeveloperName = 'Project' limit 1];
        string rId = rt.Id;
        Project__c proj = new Project__c(Name = 'testProject',
                                         OC_field__c = 'OC Impact',
                                         Project_summary__c = 'Test Summary',
                                         Project_start_date__c = date.newInstance(2013, 1, 1),
                                         Project_end_date__c = date.newInstance(2013, 12, 25),
                                         RecordtypeId = rt.id,
                                         Submit_for_Approval_by__c = date.newInstance(2018, 12, 25),
                                         Senior_Responsible_Officer_SRO__c = userSRO.Id);
        return proj;                                 
    }
    
    public static Project_Budget__c createProjectBudget(Id projId)
    {
        Project_Budget__c pb = new Project_Budget__c(Name = 'Session',
                                                     Cost_Centre__c = 'Session',
                                                     Income__c = 0,
                                                     Expense__c = 0,
                                                     Project__c = projId);
        return pb;
    }
    
    public static Project_Budget_Detail__c createProjectBudgetDetail(Id projBudgetId)
    {
        Project_Budget_Detail__c pb = new Project_Budget_Detail__c(
                                                     Paid_As__c = 'Cash',
                                                     Income__c = 0,
                                                     Expense__c = 0,
                                                     Project_Budget__c = projBudgetId);
        return pb;
    }
}

And here is the trigger code (which I haven't touched):
trigger EventTrigger on Event (before insert, before update) {

    Event[] eventToUpdate = trigger.new;
    Clients__c clientInfo = new Clients__c();
    Project__c projectInfo = new Project__c();
    
    for (Event e : eventToUpdate)
    {
        if(e.WhatId != Null)
        {
            If(string.valueOf(e.WhatId).startsWith('a0E'))
            {
                clientInfo = [SELECT ID, Name from Clients__c Where ID = :e.WhatId];
                e.Calendar_Title__c = clientInfo.Name + ': ' + e.Subject;
            }
            
            If(string.valueOf(e.WhatId).startsWith('a04'))
            {
                projectInfo = [SELECT ID, Name from Project__c Where ID = :e.WhatId];
                e.Calendar_Title__c = projectInfo.Name + ': ' + e.Subject;
            }
        
        }
    }

}

And here is the error message I get:
15:43:17:411 EXCEPTION_THROWN [13]|System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, EventTrigger: execution of BeforeInsert

Thanking you in advance.
Best Answer chosen by Nitzan Marinov
Abhishek BansalAbhishek Bansal
Hi,

Please try with the below test class :
private class TESTCLASS_EventTrigger {
static testMethod void validateEventTrigger() {

   datetime myDateTime =
   datetime.newInstance(2012, 1, 1);
   
Clients__c c = TestUtilities.insertClient();
insert c;
Event e = new Event(Subject='Test Class Call', WhatID =c.id,
                    DurationInMinutes=30, StartDateTime=myDateTime);

insert e;

// Retrieve the new Event
e = [SELECT ID, Calendar_Title__c FROM Event WHERE Subject = 'Test Class Call'];
System.debug('Calendar_Title__c: ' + e.Calendar_Title__c);

// Test that the trigger correctly updated the price
System.assertEquals('Camilla Ferdinand: Test Class Call', e.Calendar_Title__c);
}
}

Let me know if you have any issue.

Thanks,
Abhishek

All Answers

Abhishek BansalAbhishek Bansal
Hi,

Please try with the below test class :
private class TESTCLASS_EventTrigger {
static testMethod void validateEventTrigger() {

   datetime myDateTime =
   datetime.newInstance(2012, 1, 1);
   
Clients__c c = TestUtilities.insertClient();
insert c;
Event e = new Event(Subject='Test Class Call', WhatID =c.id,
                    DurationInMinutes=30, StartDateTime=myDateTime);

insert e;

// Retrieve the new Event
e = [SELECT ID, Calendar_Title__c FROM Event WHERE Subject = 'Test Class Call'];
System.debug('Calendar_Title__c: ' + e.Calendar_Title__c);

// Test that the trigger correctly updated the price
System.assertEquals('Camilla Ferdinand: Test Class Call', e.Calendar_Title__c);
}
}

Let me know if you have any issue.

Thanks,
Abhishek
This was selected as the best answer
Nitzan MarinovNitzan Marinov
Thanks Abnishek,

That even helped me to tidy up the code and make it neater:

@isTest
private class TESTCLASS_EventTrigger {
static testMethod void validateEventTrigger() {

    string mySubject = 'Test Class Call';
    datetime myDateTime = datetime.newInstance(2012, 1, 1);
    integer myDuration = 30;
   
Clients__c c = TestUtilities.insertClient();
    insert c;
Event e = new Event(Subject=mySubject, WhatID = c.id,
                    DurationInMinutes=myDuration, StartDateTime=myDateTime);
       insert e;

// Retrieve the new Event
e = [SELECT ID, Calendar_Title__c FROM Event WHERE Subject = :mySubject];
System.debug('Calendar_Title__c: ' + e.Calendar_Title__c);
    

// Test that the trigger correctly updated the price
System.assertEquals(c.Name + ': ' + mySubject, e.Calendar_Title__c);
}
}

I'm starting to get the login of this :-)