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
bharath kuppalabharath kuppala 

test class for before update trigger

Please help me in test class for these. Its a critical req, please do the need as soon as possible
thanks in advance
trigger OpportunityBeforeUpdate on Opportunity (before update) {


 System.debug('***********************Before Update');
 
 //Update OQMStage Date
 if(TKT_Case_HelperClass.firstRun){
    if(Util.canTrigger('OQM01'))
    {
        Util.MyLog('## OQM01 begin prepare');
        System.debug('**************OQM01Trigger');
        // Create a list of opportunities to update 
        Map<Id,String> OQM01OpportunitiesID=new Map<Id,String>();
 
   System.debug('**************Trigger New Size'+Trigger.New.size());
   
   
   
         // Fetch Opportunity record updated
         for (Integer i = 0; i < Trigger.New.size(); i++) {
            // Keep Opportunity which have StageName field modified
            if (Trigger.old[i].StageName != Trigger.new[i].StageName) {
                // Add modified opportunity to ListOppty
                 System.debug('**************OQM Not Equal Old'+Trigger.old[i].StageName+'new'+Trigger.new[i].StageName);
                OQM01OpportunitiesID.put(Trigger.new[i].Id,Trigger.new[i].StageName);
            }
            System.debug('**************OQM outside if old'+Trigger.old[i].StageName+'new '+Trigger.new[i].StageName); 
        }
        if(OQM01OpportunitiesID.size()>0){   
              System.debug('**************Call class OQM01Trigger');
          //  OQM01Opportunity.SetOQMStageDate(OQM01OpportunitiesID);
            OQM01Opportunity.updateOQMStageDate(Trigger.new);
            
            
        }
        else 
            Util.MyLog('## OQM01 no Opportunities to treat on '+Trigger.new.size()+' opportunities');
        Util.MyLog('## OQM01 end');
    }
 
 //End
 

/**
//NAJLAE CASE[00017172]
list<Opportunity > LstOpA = new list<Opportunity >();
 for(integer i =0; i<trigger.new.size(); i++) 
  {
        if(Trigger.new[i].Sales_Manager__c!=null)
        {System.debug('CASE[00017172]');
        LstOpA.add(Trigger.new[i]);}
            
  }
if(LstOpA.size()>0) { System.debug('LstOpA.size()'+LstOpA.size()); MAJSalesManageOwner.GetSalesManageEmail(LstOpA);}
// END NAJLAE
**/
//NAJLAE CASE[00021314]
list<Opportunity > LstOpA = new list<Opportunity >();
MAJSalesUser.UpdateInsideSalesName(Trigger.new);
// END NAJLAE


    //AP03 (MLG 28/03/2009) New Opportunity's owner is inserted in AccountTeam with Read access
        //if  Trigger.old[i].OwnerId <> Trigger.new[i].OwnerId  AND Opportunity.RecordType = « CORE - Opportunity Record Type »
    if(Util.canTrigger('AP03')){
        System.Debug('## AP03 begin prepare');
        Opportunity [] AP03Opportunities=new Opportunity[]{};   
      
      for(Integer i = (Trigger.new.size()-1); i >=0 ; i--) {
       if( ((String)Trigger.new[i].OwnerId).substring(0,3) == '005' ){
            Trigger.new[i].Owner__c = Trigger.new[i].OwnerId;}
        else{
            // in case of Queue we clear out our copy field
            Trigger.new[i].Owner__c = null;
        }
        if(Trigger.new[i].OwnerId <> Trigger.old[i].OwnerId)
        if(String.ValueOf(Trigger.new[i].RecordTypeId).equals(Util.RtypeId_CoreOppRtype)) 
        {
            AP03Opportunities.add(Trigger.new[i]);
            
        }   
      } 
        System.Debug('## AP03 end prepare');
        if(AP03Opportunities.size()>0){  
            AP03Opportunity.setUserInAccountTeamReadAccess(AP03Opportunities);
        }else System.Debug('## AP03 no Opportunities to treat on '+Trigger.new.size()+' opportunities');
     }//bypass
     
      //Object (s) : Opportunity

//What : When Opportunity status get "Refused" By Salesman  
//then change Opportunity owner to Telesales who first created the opportunity. 
//Telesales user Id has been stored into the text field "FirstOwnerId__c" 
//on Opportunity thanks to Workflow WF067_Opportunity_First_Owner_Id


if(Util.canTrigger('OPP01'))
{
    Util.MyLog('## OPP01 begin prepare');
    Opportunity [] OPP01Opportunities=new Opportunity[]{};   
  
  for(Integer i = (Trigger.new.size()-1); i >=0 ; i--) 
  {
        System.Debug(Trigger.new[i]);
         if(Trigger.old[i].Opportunity_Sales_Status__c != Trigger.new[i].Opportunity_Sales_Status__c)
          if(Trigger.new[i].Opportunity_Sales_Status__c == Config.EMG_STATUS_GET_REJECTED)
            OPP01Opportunities.add(Trigger.new[i]);
  } 
    Util.MyLog('## OPP01 end prepare');
    if(OPP01Opportunities.size()>0){   
        OPP01Opportunity.modifyOpportunityOwnerOnOpportunity(OPP01Opportunities);
    }else Util.MyLog('## OPP01 no Opportunities to treat on '+Trigger.new.size()+' opportunities');
 }//bypass
   
    
    System.Debug('## AP02 begin prepare');
    Set<Id> SetAccountIds = new Set<Id>();
    Set<Id> SetBPIds = new Set<Id>();
    Map<Id,Account> mapAccount = new Map<Id,Account>();
    Map<Id,Account> mapBP = new Map<Id,Account>();
    for(Opportunity opp: Trigger.new)
    {
         SetAccountIds.add(opp.AccountId);
         if(opp.BusinessPartner__c!=null)SetBPIds.Add(opp.BusinessPartner__c);
    }
    mapAccount = Util.getAccountMapFromOpportunities(SetAccountIds);
    mapBP = Util.getBPMapFromOpportunities(SetBPIds);
    //1:récupérer Opportunity.AccountId
    for(Opportunity opp: Trigger.new)
    {
        if(opp.AccountId!=trigger.oldMap.get(opp.id).accountId)
        {
        
        if(mapAccount.get(opp.AccountId).City__c!=null)opp.AccountCitynew__c=mapAccount.get(opp.AccountId).City__c;else opp.AccountCitynew__c=null;
        if(mapAccount.get(opp.AccountId).State_Province__c!=null)opp.Account_State_Province__c=mapAccount.get(opp.AccountId).State_Province__c;else opp.Account_State_Province__c=null;
        if(mapAccount.get(opp.AccountId).Industry!=null)opp.Account_Vertical__c=mapAccount.get(opp.AccountId).Industry;else opp.Account_Vertical__c=null;
        if(mapAccount.get(opp.AccountId).ZipCode__c!=null)opp.Account_Zip_Code__c=mapAccount.get(opp.AccountId).ZipCode__c;else opp.Account_Zip_Code__c=null;
        
        }
        if(opp.BusinessPartner__c != null && opp.BusinessPartner__c!=trigger.oldMap.get(opp.id).BusinessPartner__c)
        {
        
        if(mapBP.get(opp.BusinessPartner__c).MasterDistributor__c!=null)
        {
            opp.BP_Master_Distributor_text__c=mapBP.get(opp.BusinessPartner__c).MasterDistributor__r.name;
            opp.Nombredejours__c=mapBP.get(opp.BusinessPartner__c).MasterDistributor__r.Nombredejours__c;
            
        }
        else {opp.BP_Master_Distributor_text__c=null; opp.Nombredejours__c=0;}
        if(mapBP.get(opp.BusinessPartner__c).ownerId!=null)opp.BPOwnernew__c=mapBP.get(opp.BusinessPartner__c).owner.firstname+' ' +mapBP.get(opp.BusinessPartner__c).owner.lastname;
        if(mapBP.get(opp.BusinessPartner__c).Parent.Name!=null)opp.Primary_Partner_PARENT_new__c=mapBP.get(opp.BusinessPartner__c).Parent.Name;else opp.Primary_Partner_PARENT_new__c=null;
        if(mapBP.get(opp.BusinessPartner__c).PartnerType__c!=null)opp.BusinessPartnerReportingCategory__c=mapBP.get(opp.BusinessPartner__c).PartnerType__c;else opp.BusinessPartnerReportingCategory__c=null;
       
        }
    }
    
    // Modif MB
    List<Id> opportunitiesIdsWithAttachment = new List<Id>(); 
    for(Id opptyId : Trigger.newMap.keyset()){ 
      if(trigger.newMap.get(opptyId).Configuration_Attached__c == true && trigger.oldMap.get(opptyId).Configuration_Attached__c == false){
        opportunitiesIdsWithAttachment.add(opptyId);
      }
    }
    if(opportunitiesIdsWithAttachment.size()>0){
      OPP01Opportunity.blockOpportunityUpdateWithNoAttachment(opportunitiesIdsWithAttachment, Trigger.newMap);
    }
//NAJLAE_BOM
    List<Id> opptiesToCheck = new List<id>();
    System.debug('##NAJLAE Start ');
         Id EMGS = [Select id , Name from profile where Name='EMG - Direct Touch OQM Simple (NA)'].id;
         System.debug('## EMGS :'+EMGS );
         Id EMGSTas = [Select id , Name from profile where Name='EMG - Direct Touch OQM Simple TAS (NA)'].id;
         System.debug('## EMGSTas :'+EMGSTas );
/**         Id EMGTas = [Select id , Name from profile where Name='ESD - Direct Touch OQM TAS'].id;
//         System.debug('## EMGTas :'+EMGTas );
//         Id Admin = [Select id , Name from profile where Name='System Administrator'].id; 
//        System.debug('## Admin:'+Admin);
        System.debug('## Userinfo.getProfileId():'+Userinfo.getProfileId());**/
//NAJLAE Case[00018531]
list<Opportunity> OppSecondOwner  = new list<Opportunity>(); 
//END NAJLAE Case[00018531]                  
            for(Opportunity oppty : trigger.new){
        System.debug('## oppty.Configuration_Attached__c:'+oppty.Configuration_Attached__c);
        System.debug('## oppty.Configuration_Attached__c:'+oppty.Configuration_Attached__c);  
                System.debug('## oppty.Amount:'+oppty.Amount);          //if(oppty.Configuration_Attached__c == false && oppty.StageName == '4-Offer Made' && oppty.Amount > 50000)
            
                if( (Userinfo.getProfileId()==EMGS||Userinfo.getProfileId()==EMGSTas) && oppty.Configuration_Attached__c == false && (oppty.ALUProbability__c== '100' ||oppty.ALUProbability__c== '60'||oppty.ALUProbability__c== '70'||oppty.ALUProbability__c== '80'||oppty.ALUProbability__c== '90' )   && oppty.Amount >= 50000){
                     opptiesToCheck.add(oppty.id);
                    System.debug('#HERE !!!');
                    }
   
                /**NAJLAE Case[00018531]
                System.debug('oppty.Secondary_Owner__c'+ oppty.Secondary_Owner__c);
                System.debug('oppty.BusinessPartner__c'+ oppty.BusinessPartner__c);
                if(oppty.BusinessPartner__c!=null && oppty.Secondary_Owner__c==null)
                {
                    OppSecondOwner.add(oppty);
                }
                 END Case[00018531]**/
}
    /**NAJLAE Case[00018531]
    System.debug('oppSecondOwner.size()'+ oppSecondOwner.size());
    
    if(oppSecondOwner.size()>0){
        OPP01Opportunity.MAJSecondaryOwner(OppSecondOwner);
    }
     END Case[00018531]**/
     
    System.debug('## opptiesToCheck:'+ opptiesToCheck);
    if(opptiesToCheck.size()>0){
        OPP01Opportunity.blockOpporunityUpdateWithNoValidConfigFile(opptiesToCheck, Trigger.newMap);
    }
// NAJLAE END
        
    // Modif MB
    if(Util.canTrigger('Opp_Ctt_Role')){
        
      if(OPP01Opportunity.bypassContactRoleCheck != true && !OPP01Opportunity.userProfileIsBypassed(Userinfo.getUserId())){  
         Map<id, Opportunity> nonClosedCancelledOpps =  new Map<id, Opportunity>();
        for(Opportunity opp : trigger.new){
          if(opp.StageName != '9-Closed Cancelled' && opp.RunRate__c != true){
            nonClosedCancelledOpps.put(opp.id, opp);
          }
        }
        if(nonClosedCancelledOpps.size()>0){
          OPP01Opportunity.blockOpportunityUpdateWithNoValidContactRole(nonClosedCancelledOpps, trigger.oldMap);  
        }
      }
    }
    
    //Najlae Case[00016890]
    
        MajAmount.MajAmountfromParent(Trigger.New);
    //End Najlae Case[00016890]
    TKT_Case_HelperClass.firstRun=false;
 }
}
Raj VakatiRaj Vakati
You need to do it like below and please repeat all conditions  for  Util.canTrigger('OQM01') ;

 
@isTest
private class OpportunityBeforeUpdateTest {

   static testMethod void testCase1() {
	   TKT_Case_HelperClass.firstRun = true ;
	   Util.canTrigger('OQM01') ; 
	   
	   Profile pf= [Select Id from profile where Name='System Administrator']; 
        
        String orgId=UserInfo.getOrganizationId(); 
        String dateString=String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','') ;
        Integer RandomId=Integer.valueOf(Math.rint(Math.random()*1000000)); 
        String uniqueName=orgId+dateString+RandomId; 
        User uu=new User(firstname = 'ABC', 
                         lastName = 'XYZ', 
                         email = uniqueName + '@test' + orgId + '.org', 
                         Username = uniqueName + '@test' + orgId + '.org', 
                         EmailEncodingKey = 'ISO-8859-1', 
                         Alias = uniqueName.substring(18, 23), 
                         TimeZoneSidKey = 'America/Los_Angeles', 
                         LocaleSidKey = 'en_US', 
                         LanguageLocaleKey = 'en_US', 
                         ProfileId = pf.Id
                        ); 
        
        
        insert uu;
		
		
	    Account a = new Account(Name = 'Test');
        insert a;
        
        Opportunity o = new Opportunity();
        o.name = 'Test';
        o.AccountId = a.Id;
        o.StageName = 'Closed Lost';
        o.CloseDate = date.today();
        o.Type = 'New Customers';
        o.Sales_Manager__c = uu.Id ;
        insert o;
		  o.StageName = 'Closed Won';
      update o ;
		
       
    }
}

 
bharath kuppalabharath kuppala
@isTest
(seeAllData=true)
public class Test_OpportunityTrigger {
    
    
    static testMethod void OpportunityCodeCoverage()
    {
        
         Profile P = [select Name from Profile where Name = 'EMG - Business Analyst' Limit 1];
        UserRole ur = new UserRole(Name='Level Test', DeveloperName='Level1_Test');
        insert ur;    
        
        user u = new User(Alias = 'st', Email='user@tes1.com', 
        EmailEncodingKey='UTF-8', LastName='Test', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = p.Id, UserRoleId=ur.id,
        TimeZoneSidKey='America/Los_Angeles', UserName='user@tes1.com');
        
        insert u;
    
     System.runAs(u)
        {       
          
       Country__c  c=[SELECT Country__c,Name FROM Country__c where Name='India'];
        
        Account acc1=new Account();
        acc1.Name='account test';
        acc1.Street1__c='chennai';
        acc1.ZipCode__c='600043';
        acc1.City__c='chennai';
        acc1.Country__c=c.Id;
        acc1.Type='Prospect';
        acc1.Verticals__c='Education';
        acc1.AccountClassification__c='Unknown';
         insert acc1;
        
        Opportunity opp=new Opportunity();
        opp.Name='TestOpportunity';
        opp.StageName='8-Closed Lost';
        opp.Competitor__c='3COM';
        opp.WonLostCancelledReason__c='    Best Price';
        opp.CloseDate=date.today();
        opp.AccountId=acc1.Id;
        opp.DealReg__c=true;            
        insert opp;
        if(opp.DealReg__c)
       {
           if(opp.Deal__r.Deal_Account_Country__c=='USA' || opp.Deal__r.Deal_Account_Country__c=='Canada')
           {opp.CurrencyIsoCode = 'USD';}
       }
        
         Opportunity o=[Select id,Name,StageName,Country__c from opportunity where Id=:opp.Id];
         o.StageName='9-Closed Cancelled';
        o.Competitor__c='3COM';
        o.Opportunity_Sales_Status__c='Rejected';
       
        o.RunRate__c=false;
        
        OPP01Opportunity.bypassContactRoleCheck = false;
        OPP01Opportunity.userProfileIsBypassed(u.id);
        update o;
       
        Opportunity o1=[Select id,Name,StageName,Country__c from opportunity where Id=:opp.Id];
         o1.StageName='9-Closed Cancelled';
        o1.Competitor__c='3COM';
        o1.Opportunity_Sales_Status__c='Rejected';
       
        o1.RunRate__c=true;
        update o1;
       
       
       
        }
        
        
    }
    
   // Update the Stage ,Opportunity Owner  and Opportunity_Sales_Status__c 
   static testMethod void OpportunityCodeCoverage01()
    {
        
         Profile P = [select Name from Profile where Name = 'EMG - Business Analyst' Limit 1];
        UserRole ur = new UserRole(Name='Level Test', DeveloperName='Level1_Test');
        insert ur;    
        
        user u = new User(Alias = 'st', Email='user@tes1.com', 
        EmailEncodingKey='UTF-8', LastName='Test', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = p.Id, UserRoleId=ur.id,
        TimeZoneSidKey='America/Los_Angeles', UserName='user@tes1.com');
        insert u;
    
       System.runAs(u)
        {     
         
          Test.startTest();
        Country__c  c=[SELECT Country__c,Name FROM Country__c where Name='India' limit 1];
        
        State_Province__c sp = new State_Province__c(Name = 'Cauca' , Country__c = c.id );
        
        //Create a First Account
        Account acc=new Account();
        acc.Name='account test';
        acc.Street1__c='New Jersey';
        acc.ZipCode__c='600043';
        acc.City__c='New Jersey';
        acc.Country__c=c.Id;
        acc.Type='Prospect';
        acc.Verticals__c='Education';
        acc.AccountClassification__c='Unknown';
        acc.State_Province__c  = sp.id;
        insert acc;
        
        //Create a Second Account
        Account acc2=new Account();
        acc2.Name='account test2';
        acc2.Street1__c='London';
        acc2.ZipCode__c='60431';
        acc2.City__c='London';
        acc2.Country__c=c.Id;
        acc2.Type='Prospect';
        acc2.Verticals__c='Services';
        acc2.AccountClassification__c='Unknown';
        acc2.State_Province__c  = sp.id;
        insert acc2;
        
        Opportunity opp = new Opportunity();
        opp.Name='TestOpportunity';
        opp.StageName='8-Closed Lost';
        opp.Opportunity_Sales_Status__c = 'Submitted';
        opp.Competitor__c='3COM';
        opp.WonLostCancelledReason__c='    Best Price';
        opp.CloseDate=date.today();
        opp.AccountId=acc.Id;
        opp.DealReg__c=true;
        opp.Owner__c = '00520000005vm9BAAQ';
        opp.Opportunity_Sales_Status__c = 'Submitted';
        opp.BPOwnernew__c = 'Silke FRAEDRICH';
        opp.Primary_Partner_PARENT_new__c = 'NOKIA';
        opp.BusinessPartnerReportingCategory__c = 'Indirect Reseller';
        opp.Configuration_Attached__c  = true;
        opp.AccountCitynew__c  = 'New Jersey';
        opp.Account_State_Province__c = sp.id;
        opp.Account_Vertical__c = 'Education';
        opp.Account_Zip_Code__c = '600043';
        opp.RecordTypeid  = '01220000000EdDV';
        opp.RunRate__c = false;
        insert opp;
      
       
       String value  = Config__c.getValues('EMGStatusGetRejected').Value__c;
       String rt =  'CORE - Opportunity Record Type';
       
       
       
        opp.AccountId=acc2.Id;
        opp.StageName = '4-Offer Made';
        opp.Opportunity_Sales_Status__c = value;
        opp.ALUProbability__c = '90';
        string ap = '18500';
        opp.Amount = decimal.valueOf(ap);
        opp.AccountCitynew__c  = null;
        opp.Account_Vertical__c = null;
        opp.Account_Zip_Code__c = null;
        opp.Owner__c = '0050J000007Ybyz';
        OPP01Opportunity.bypassContactRoleCheck = false;
        OPP01Opportunity.userProfileIsBypassed(u.id);
        opp.RecordTypeid  = '01220000000cRy9';
        update opp;
        
        List<Opportunity> oppList = new List<Opportunity>();
        oppList.add(opp);
        update oppList;
        
        OQM01Opportunity.updateOQMStageDate(oppList);
        Util.myLog('Rupesh');
        }
       Test.stopTest();
      }
      
      
 This test class written by me. But code coverage is 65% i tried everything but unable to get above 65%. Please help me     
   
}
Amit Chaudhary 8Amit Chaudhary 8
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Pleasse check below post sample test class
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

You write a test class for this the same way that you would any other:
Set up some data for the Trigger to access (in this case it looks like Account ,Contact and Opportunity)
- execute trigger - by creating record/update a record
- Verify the behaviour with asserts.

NOTE:- Dnt use SeeAllData=true
Also please let us know which lines are not covered?



Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required 
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you
bharath kuppalabharath kuppala
Line 25,32
Line 74,77,85
Line 107,108,111
Line 134 - 137
Line 143-146
Line 149-152
Line 161,165
Line 188,211

and API  version is 20