New to Apex here. I cobbled together a trigger that creates a new task whenever a certain type of opportunity is Closed - Lost, but I can't figure out how to get ANY coverage with a unit test. Does anyone see what I am doing wrong here?
Trigger:
trigger OpportunityAfter on Opportunity (after update){ Set AccountIDs = new Set(); for(Opportunity o : trigger.new){ AccountIDs.add(o.AccountId); } for(Opportunity opp : trigger.new) if(opp.StageName == 'Closed - Lost' && trigger.oldMap.get(opp.Id).StageName != opp.StageName) AccountIds.add(opp.AccountID); Task[] tasksToInsert = new Task[]{}; for (Account acc : [Select Id, Name, OwnerId from Account where Id IN :AccountIds]) for (Opportunity opp : trigger.new) if(opp.StageName == 'Closed - Lost' && opp.Business_Line__c == 'Workforce' && opp.Survey_Type__c != 'APulse' && trigger.oldMap.get(opp.Id).StageName != opp.StageName) tasksToInsert.add(new Task(WhatId=acc.Id, OwnerId=opp.OwnerId, Subject='Follow-up: ' + opp.name + ' - ' + acc.name, ActivityDate=(opp.CloseDate + 180), Description='Follow up to see how engagement initiatives are going and if Avatar can help. Refer to lost opportunity: ' + opp.name)); if(tasksToInsert != null && !tasksToInsert.isEmpty()) Database.insert(tasksToInsert); }
Test:
@isTest public class TestClass { static testMethod void myUnitTest() { //Set up user User u1 = [SELECT Id FROM User WHERE Email='[email protected]']; //Run As U1 System.RunAs(u1){ System.debug('Testing trigger... (single record validation)'); //NEW Account record Account acc = new account(); acc.Name = 'Test Account'; acc.Industry = 'Healthcare'; insert acc; //NEW Opportunity record Opportunity opp = new Opportunity(); opp.Name = 'Test Opportunity'; opp.CloseDate = System.today(); opp.StageName = 'S1 - Investigative'; opp.Type = 'Repeat Business - Wrkforce HC'; opp.AccountId = acc.Id; opp.Survey_Type__c = 'Product Name'; insert opp; opp.StageName = 'Closed - Lost'; opp.Reason_Won_Lost__c = 'Relationship'; update opp; //NEW Task record Task testTask = new task(); testTask.WhatId = acc.Id; testTask.Subject = 'Follow-up: ' + opp.name + ' - ' + acc.name; testTask.ActivityDate = (opp.CloseDate + 180); testTask.Description = 'Follow up to see how engagement initiatives are going and if we can help. Refer to lost opportunity: ' + opp.name; insert testTask; //Validate single insert System.assertEquals(acc.Id, testTask.WhatId); } } }