I've written a before update trigger and I am getting failures when I run my tests on it. In order to debug what's actually going on I would like to insert debug messages into my trigger, run my test, and view the output from those debug messages on the test results screen. How can I accomplish this?
Note: In the below trigger the issue lies in the line where I check if a record is closed. I've tried removing the comparison to check if the old record had a different status and I still get the same issue. For some reason it simply can't get the correct status/isclosed of the new record. It doesn't ever seem to see that a case has been updated to a "closed" status.
In the test method I create a new case with a status that defaults to an "open" state. Then I update it with a status that corresponds to a "closed" state. My trigger fires on this update and doesn't see a closed state.
Trigger
trigger CaseClosed on Case ( before update ) {
Boolean hasOpenTasks;
List<Task> taskList = new List<Task>();
/*
Find all of the cases that have had their statuses changed to "Closed"
Then query for all open tasks on each case.
Note 1: This trigger may need to be bulkified
*/
for( Case record : Trigger.new ) {
hasOpenTasks = false;
if( record.IsClosed && !Trigger.oldMap.get( record.Id ).IsClosed ) {
// Fetch and store the list of tasks associated with this case.
taskList = [SELECT isClosed FROM task WHERE WhatId = :record.Id AND isClosed = true];
// Check if there were any open tasks
if( taskList.size() > 0 ) {
hasOpenTasks = true;
}
else {
// do nothing.
}
// If there were open tasks: append an error message to the case and revert it to the old case.
if( hasOpenTasks ) {
record.Status = Trigger.oldMap.get( record.Id ).Status;
record.addError('Sorry, this Case can\'t be closed because there are still open tasks.');
}
}
}
}
Test Method
static testMethod void validateClosedCase() {
// Test Case object
Case c1 = new Case( Status = 'New' );
// "Open Task"
Task t1 = new Task( Status = 'In Progress', WhatId = c1.Id );
// Insert a new case and an open task associated with it
insert( c1 );
insert( t1 );
// update the case with a closed status.
c1.Status = 'Closed';
update( c1 );
// Verify that case 1 has retained its original status and remains open
Case c1_2 = [SELECT Status, isClosed FROM Case WHERE Id = :c1.Id];
System.assertEquals( 'New', c1_2.Status );
System.assertEquals( false, c1_2.isClosed );
}
trigger CaseTrigger on Case (after update) { for(Case record: [SELECT Id, (SELECT Id FROM Tasks WHERE IsClosed = FALSE) FROM Case WHERE Id IN :Trigger.new AND IsClosed = TRUE]) if(!Trigger.oldMap.get(record.Id).IsClosed && record.Tasks != null && !record.Tasks.IsEmpty()) Trigger.newMap.get(record.Id).Status.addError('You cannot close a case with open tasks.'); }