I have a simple after insert trigger which inserts a task when an account is created. I am struggling to cover the catch statement in my test class. Is there a way to cover it?
Apex Trigger
trigger Account on Account (after insert) {
AccountTriggerClass.taskInsert(Trigger.new);
}
Apex Class
public class AccountTriggerClass {
public static void taskInsert(List<Account> acc)
{
try{
List<Task> taskList = new List<Task>();
for(Account a : acc){
Task tk = new Task();
tk.Subject = 'New Task created by after insert';
tk.WhatId = a.Id;
taskList.add(tk);
}
Database.insert(taskList, false);
}
catch(exception ex){
system.debug(ex.getMessage());
}
}
}
Test Class
@isTest
public class AccountTriggerClassTest {
@isTest private static void taskInsertMethod(){
Account a = new Account();
a.Name = 'Test Account 2';
insert a;
}
}
Database.insert
returns aDatabase.SaveResult[]
that would contain success or error messages for each record attempted to be inserted. Doc. See also existing answers about blindly catching general exceptions. Typically, you'd catch an exception with a purpose/scenario in mind which makes testing it easier.