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
hlsimoneauhlsimoneau 

Trigger test class fails - trigger updates opportunity to Closed Won based on related case update

Hello,
I've written a trigger that updates an opportunity to Closed Won and sets a value (NetSuite Sales Order ID) in a custom opp field based on a related Sales Order case being updated with certain values (NetSuite Sales Order ID) and the case being closed. The trigger works great and updates values on the Opp as expected, but I'm either facing errors in my test class or running into other code/validations because I'm setting the opp to Closed Won. If it's the former, I'd appreciate any help or suggestions on how better to structure my test class and/or my trigger. If it's the later, is there anything I can put in my code to see what other code or validations are causing the problem?

I continue to get errors like this when I run the test class:
System.AssertException: Assertion Failed: Expected: Pending Sales Order, Actual: Closed Won
OR (if I comment out the line causing the above issue)
System.AssertException: Assertion Failed: Expected: 12345, Actual: null

Here's my trigger:
trigger SalesOrderUpdateStageToClosedWon on Case (after Update) {
List<Opportunity> oppList=new List <Opportunity>();
set<id> oppIds = new Set<id>();
RecordType rt = [SELECT Id,Name,SobjectType FROM RecordType WHERE Name = 'Sales Order Case' AND SobjectType = 'Case' LIMIT 1];

for(case c:trigger.new)
{
oppIds.add(c.Opportunity__c);
}
Map<id,Opportunity>oppMap=new Map<id,Opportunity>([Select Id from Opportunity 
Where id in :oppIds]);
List<case> myCases = [select ID from case where ID in :oppIds]; 
Set<ID> myOppsIDs = new Set<ID>();

for (case c : myCases)
{
myOppsIDs.add(c.Opportunity__c);
}
for (case c :trigger.new)
{
if(c.RecordTypeId==rt.Id&&c.NetSuite_Sales_Order_ID__c <> null&&c.Status=='Closed'){
opportunity opp=oppMap.get(c.Opportunity__c);
opp.StageName='Closed Won';   
opp.NetSuite_Sales_Order_ID__c=c.NetSuite_Sales_Order_ID__c;       
oppList.add(opp);
}


}

update oppList;
}


And here's my test class:
@isTest (SeeAllData=True)
public class SalesOrderUpdateStageToClosedWon_Test{

    
    static testMethod void testOppClosedWon(){ 
    test.startTest();  
    //Create Account and Opportunity Record
    Date dToday = Date.today();
    Account acc = new Account(Name = 'Test Account');
    insert acc;
    Opportunity oppRec = new Opportunity (Name = 'Test Opportunity', AccountId = acc.Id, StageName='Pending Sales Order', 
    CloseDate=dTODAY,Ship_Date__c=dTODAY+1,Customer_Notes_Completed__c=true,Approval_Status__c='Approved',
                                          Number_of_Locations__c = 1,Renewal_Term_months__c=1,RecordTypeID='012R0000000DBjt');
     insert oppRec;
        
    //Create Case
  
    
   
    
    Case caseRec = new Case(Opportunity__c = oppRec.Id, POS_Install_Date__c=Date.newInstance(2014,12,31),RecordTypeID='012R00000004y6K',Status='Closed',NetSuite_Sales_Order_ID__c='12345');
    system.debug('About to insert Case' + caseRec);
    insert caseRec;
    
    
    System.Debug('Value of Insert Opp ID ------------------------>' + oppRec.Id);
    System.Debug('Value of Insert Opp StageName ------------------------>' + oppRec.StageName);   
    
    Case testCase = [Select Opportunity__c,NetSuite_Sales_Order_ID__c from Case where Id =: caseRec.Id];
    Opportunity testOpp = [Select Id,StageName, CloseDate,NetSuite_Sales_Order_ID__c from Opportunity where Id =: oppRec.Id];
    
    //Id caseRecId = caseRec.OpportunityId;
    System.assertEquals(testOpp.Id, testCase.Opportunity__c);
    System.assertEquals(testOpp.StageName,'Closed Won');
    System.assertEquals(testCase.NetSuite_Sales_Order_ID__c,testOpp.NetSuite_Sales_Order_ID__c);
    test.stopTest();
    }
    
}



Best Answer chosen by hlsimoneau
Vishant ShahVishant Shah
Hi,

Looking at your test class and trigger, your trigger will fire only after update of a case, at no point after inserting you update the case status to Closed.

At line 31 add the following

testCase.Status = 'Closed';
testCase.NetSuite_Sales_Order_ID__c = '12345';
update testCase;

this should solve your issue.

Ta
Vish

All Answers

Vishant ShahVishant Shah
Hi,

Looking at your test class and trigger, your trigger will fire only after update of a case, at no point after inserting you update the case status to Closed.

At line 31 add the following

testCase.Status = 'Closed';
testCase.NetSuite_Sales_Order_ID__c = '12345';
update testCase;

this should solve your issue.

Ta
Vish
This was selected as the best answer
Vishant ShahVishant Shah
Sorry add it on line before you get the opp on line 30;

Vish
hlsimoneauhlsimoneau
Thank you, Vish! Adding that bit of code at line 30 resolved the issue and gave me the test coverage I needed! Forgot that I was only firing the trigger on case update, so thanks for the second set of eyes!
Shikha ShetShikha Shet
Hi,
I am facing the similar kind of issue. 
I am having a custom object Employee__c, where I have written a trigger to update a custom field Employee_Name__c on change of owner field in Employee__c. The trigger works as expected. But still my test class fails saying as Expected 'first last', Actual 'null', though code is running as desired. Below is my code. Can anyone tell me why my test class fails?

trigger UpdateNameOnOwnerChange on Employee__c (before update) 
{
    Map<Id,String> UserMap = new Map<id,String>();
    List<User> uList = [select Id, Name from User];
    for(User u : uList)
    {
        UserMap.put(u.Id, u.Name);
    }
   // List<Employee__c> empList = new List<Employee__c>();
    for(Employee__c emp : trigger.new)
    {
        Employee__c empold = trigger.oldmap.get(emp.Id);
        String oldempOwn = empold.OwnerId;
        String newempOwn = emp.OwnerId;
        system.debug('OwnerId new '+newempOwn+' old owner Id '+oldempOwn );
        if(newempown != oldempOwn)
        {
            //system.debug('emp owner name'+emp.Owner.Username);
            if(UserMap.containskey(emp.OwnerId))
            {                                
               // emp.Employee_Name__c= usermap.get(emp.OwnerId).name;
                system.debug('map val'+usermap.get(emp.ownerid));
                emp.Employee_Name__c = usermap.get(emp.ownerid);
                //empList.add(emp);
                system.debug('Name is '+emp.Employee_Name__c);
            }            
        }
    }

Below is my test class for the same.

@istest
public class TestUpdateOwnerEmp 
{
  @testsetup
    static void setup()
    {
        //UserRole r = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role');
        //insert r;
        User u =new User(
        ProfileId = [select id from profile where name = 'Std Cont Cust Obj'].Id,
           FirstName = 'first0',                
               LastName = 'last0',
               Email = 'puser000@gmail.com',
               UserName = 'puser000@gmail.com',
               CompanyName = 'Test',
               Title = 'title',
               Alias = 'alias',
               TimeZoneSidKey = 'America/Los_Angeles',
               EmailEncodingKey = 'UTF-8',
               LanguageLocalekey = 'en_US',
               LocaleSidKey ='en_US');
               //UserRole = r.Id);
    insert u;
        User u1 =new User(
        ProfileId = [select id from profile where name = 'Std Cont Cust Obj'].Id,
               FirstName = 'first',
                 LastName = 'last',
               Email = 'puser001@gmail.com',
               UserName = 'puser001@gmail.com',
               CompanyName = 'Test',
               Title = 'title',
               Alias = 'alias',
               TimeZoneSidKey = 'America/Los_Angeles',
               EmailEncodingKey = 'UTF-8',
               LanguageLocalekey = 'en_US',
               LocaleSidKey ='en_US');
        insert u1;
        
        Account a = new Account(Name = 'Test');
        insert a;
        
        Contact c = new Contact(Firstname = 'First', Lastname = 'Last', email = 'firstlast@test.com', accountId = a.id);
        insert c;
        
        Employee__c emp = new Employee__c();
        //emp.AccountId__c = '0012800000tbM5E';
        emp.ContactId__c = c.Id;
        emp.Employee_Name__c = 'test';
        emp.Salary__c = 12200;
        emp.OwnerId = u.Id;
        insert emp;
        
    }
    
    static testmethod void testownerchange()
    {
        test.startTest();
        user u = [select Id, name from User where UserName = 'puser001@gmail.com'];
        //User u = [select id,Name from User];
        Employee__c emp = [select Id,OwnerId, Employee_Name__c from Employee__c];
        system.debug('Employee '+emp);
        emp.OwnerId = u.Id;        
        
        Database.SaveResult res = Database.update(emp,false);
        system.debug('success status '+res.isSuccess());
        //system.assertEquals(u.Name, emp.Employee_Name__c);
        
        test.stopTest();
        system.assertEquals(u.Id, emp.OwnerId);
        system.assertEquals(u.name, emp.Owner.name);
        system.assertEquals(emp.Owner.Name, emp.Employee_Name__c);
        system.debug('user name'+u.name);
        system.debug('emp name'+emp.Employee_Name__c);        
        
    }
}