You need to sign in to do that
Don't have an account?
charlie west 5
Writing Unit Test for Case/Task Trigger
Hello, I am trying to get code coverage for a trigger, but am having trouble writing unit tests. The purpose of the trigger is to throw an error when a user tries to close a Case with outstanding Tasks associated with the record. Here is the trigger
public class OpenTaskHandler { public static void getCaseList(List<Case> triggerNew, Map<id, Case> newMap){ Set<Case> newlyClosedCaseIds = new Set<Case>(); for (Case caseId : newlyClosedCaseIds) { if (caseId.IsClosed) { newlyClosedCaseIds.add(caseId); } } for (AggregateResult aggResult : [ SELECT Count(Id), WhatId From Task WHERE WhatId In :newlyClosedCaseIds AND isClosed = false Group by WhatId having Count(Id) > 0 ]) { Case openCase = (Case) aggResult.get('WhatId'); Case errorCase = newMap.get(openCase.Id); errorCase.addError('Cannot close case since there are non closed tasks: ' + errorCase.Id); } }Here is one of my tests:
@isTest public class CaseTaskTriggers { @isTest public static void TestOpenTasks() { Case testCase = new Case(); testCase.Status='New'; insert testCase; Task tsk = new Task(); tsk.Subject = 'New hire has been added'; tsk.WhatId = [select Id from Case Limit 1].Id; tsk.OwnerId = UserInfo.getUserId(); tsk.Status = 'New'; insert tsk; Test.startTest(); try{ testCase.Status = 'closed'; update testCase; } Catch(Exception ee){} system.assertNotEquals(tsk.Status = 'Closed', tsk.Status = 'New', 'Cannot close case since there are non closed tasks'); test.stopTest(); }I am getting red code coverage on the if (caseId.IsClosed) {newlyClosedCaseIds.add(caseId), the Case openCase = (Case) aggResult.get('whatid') and the errorCase.addError. How do I account for these on a unit test? I am fairly new to unit testing and would love any tips/feedback. Thanks !
The very first problem I see is in line 4. You're iterating over the blank Set of Case that means it will never iterate over the loop.
The second problem I see is in Line 15 and 16. You're trying to grab Case but you'll get Case Id. So high possibility you'll get type exception error.
Thanks,
Ashish Singh.