• Chen Chen 39
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
It works very well in sandbox, but when I am trying to write a test case for deploy, it fails me.
Here is the trigger. When a lead's owner changes, it will change that lead's Sales_Rep__c  lookup field to related  value.
trigger UpdateLeadSalesRepByOwnerTrigger on Lead (before update) {
	for (Lead lead : Trigger.new)
    {
        // Query for the user alias, which has been associated with an lead.
        User queriedUser = [SELECT Alias FROM User WHERE Id = :lead.OwnerId LIMIT 1];
        
        // Query for sales rep by user alias
        Sales_Rep__c[] salesRep = [SELECT Name FROM Sales_Rep__c WHERE Name = :queriedUser.Alias];
        
        // if sales rep is unique
        if (salesRep.size() == 1)
        {
            // set lead's Sales rep
            lead.Sales_Rep__c = salesRep[0].Id;
            System.debug('from trigger');
            System.debug(lead);
        }
    }
}
Here is my test code
@isTest
private class UpdateSalesRepByOwnerTriggerTestSuite
{
	static testMethod void LeadPostiveCase()
    {
        // prepare data
        User dc = [select Id from User where Alias = 'DC' limit 1];
        User jp = [select Id from User where Alias = 'JP' limit 1];
        Sales_Rep__c dcSales = new Sales_Rep__c(Name='DC');
        Sales_Rep__c jpSales = new Sales_Rep__c(Name='JP');
        insert dcSales;
        insert jpSales;
        System.debug(dcSales);
        System.debug(jpSales);
        Lead lead = new Lead(LastName='Test Lead', Company='TestCompany', OwnerId=dc.Id, Sales_Rep__c=dcSales.Id);
        insert lead;
        System.debug(lead);
        
        // execute test
        lead.OwnerId = jp.Id;
        update lead;
        
        System.debug(lead);
        // Verify
        System.assert(lead.Sales_Rep__c==jpSales.Id);
    }
}
Here is my debug line output
14:06:12.0 (106815151)|USER_DEBUG|[13]|DEBUG|Sales_Rep__c:{Name=DC, Id=a01630000010qPTAAY}
14:06:12.0 (106859236)|USER_DEBUG|[14]|DEBUG|Sales_Rep__c:{Name=JP, Id=a01630000010qPUAAY}
14:06:12.0 (208033855)|USER_DEBUG|[17]|DEBUG|Lead:{LastName=Test Lead, Company=TestCompany, OwnerId=00536000001pazlAAA, Sales_Rep__c=a01630000010qPTAAY, Id=00Q63000001eiDhEAI}
14:06:12.0 (254358735)|USER_DEBUG|[15]|DEBUG|from trigger
14:06:12.0 (255011803)|USER_DEBUG|[16]|DEBUG|Lead:{Id=00Q63000001eiDhEAI, IsDeleted=false, Company=TestCompany,  Sales_Rep__c=a01630000010qPUAAY}
14:06:12.0 (294976862)|USER_DEBUG|[23]|DEBUG|Lead:{LastName=Test Lead, Company=TestCompany, OwnerId=00536000001pb13AAA, Sales_Rep__c=a01630000010qPTAAY, Id=00Q63000001eiDhEAI}
What I see here, the trigger is fired, but somehow it only saved the changed owner but did not save the change of Sales_Rep__c.

Any advise would be appreciated.