+ Start a Discussion
MikeGillMikeGill 

Requery records in test class not working (before insert trigger)

Usual story trigger working fine, test class working to 86%. But can't seem to get the last part.

 

Here is the class (called by before insert trigger on opportunity).

 

The trigger is updating the type field on the account from 'Lead Acct' to 'Opportunity Acct'

 

 System.assertEquals(opp.Account.Type, 'Opportunity Acct') - this should equal, I could be late and something obvious, but I can't spot it.

 

Any help  appreciated 

 

public with sharing class OpportunityTriggerHandler {
	
		/**
		*	@author			Mike Gill
		*	@date			28/07/11
		*	@description	Update account type based on certain criteria
		*/

     
     public OpportunityTriggerHandler(){}
	
	//TODO: Add user custom persmission check
	
	 public void OnBeforeInsert(Opportunity[] newOpps){
	 	
		List<Account> accs = new List<Account>();
		
		for (Opportunity opp:newOpps){
			
			if (opp.Type == 'Lead Acct'){
				accs.add( new Account (id=opp.AccountId, Type = 'Opportunity Acct' ));
			}
			
		}
		
		update accs;  
     }
     
}

 

And here is the test class

 

@isTest
private class TestOpportunityTriggerHandler {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Test Scenarios for Opportunity Trigger Handler
	*  	TODO: 			
	*/
	
	static List<Account> accounts;
	static List<Opportunity> opps;
	static List<Contact> contacts;
	
	static {
			
			// Empty Lists	
			accounts = new List<Account>();
    		opps = new List<Opportunity>();
    		contacts = new List<Contact>();
		
			// Fetch profile id
     		Profile p = [select id from Profile where name = 'Standard User'];
     		
     		// Create user for tetsing
     		User u = new User ( alias = 'testme', email = 'testme@noemail.com', emailencodingkey = 'UTF-8', lastname = 'test',languagelocalekey = 'en_US', 
     		localesidkey = 'en_US', profileid = p.Id, country = 'United Kingdom', timezonesidkey = 'Europe/London', username = 'testme@noemail.com');
     		insert u;
     		
     		// Add  Accounts to the list to be inserted	
     		for (Integer i = 0; i<1; i++){
     			Account a = new Account(
     			Name = 'Test' + i,
     			Type = 'Lead Acct',
     			BillingState = 'CA',
     			Industry = 'Business Services',
     			OwnerId = u.Id
     			);
     			accounts.add(a);
     		}
     		
     			insert accounts;
     	
     		
     		// Add Contacts to the list to be inserted
     		for (Account a: accounts){
     			
     			Contact c = new Contact();
     			c.FirstName = 'Test First';
     			c.LastName = 'Test Last';
     			c.LeadSource = 'Call In';
     			c.AccountId = a.Id;
     			contacts.add(c);
     			
     		}
     		
     		insert contacts;
     	
     		// Add Opps
     		for (Account a: accounts){
     			
     			
     			
     			Opportunity o = new Opportunity();
     			o.Name = 'Test Opp';
     			o.AccountId = a.Id;
     			o.CloseDate = Date.today();
     			o.StageName = '1-Qualified Prospect';
     			opps.add(o);
     			
     		}
  	
		
	}
	
    static testMethod void myUnitTest_CreateOpp() {
    	
    /**
    * @description	Test related account type is set to Opportunity Acct on create of opportunity
    */
    
    		test.startTest();
       	
       		// Check account type is Lead Acct before insert
       		for (Account acc:accounts){
       			System.assertEquals(acc.Type, 'Lead Acct');
       		}	
     	
     		
     		// Insert opps
     		insert opps;
     		
     		
     		// Check records
     		System.debug(Logginglevel.ERROR, 'EB/DEBUG TEST: Number of accounts created is'+ accounts.size() + ' id=' + accounts[0].Id);
     		System.debug(Logginglevel.ERROR, 'EB/DEBUG TEST: Number of contacts created is ' + contacts.size() + ' id=' + contacts[0].Id);
     		System.debug(Logginglevel.ERROR, 'EB/DEBUG TEST: Number of opps created is ' + opps.size() + ' id='+ opps[0].Id);

   		
   			// Query for newly inserted opps
     		List<Opportunity> o = [select Id, Account.Type  from Opportunity where Id in: opps];
   			
   			for (Opportunity opp:o){
   				System.assertEquals(opp.Account.Type, 'Opportunity Acct');
   			
   			}
       		
       		       	
       		// End test
       		test.stopTest();
       		
    }
  
}

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
MikeGillMikeGill

Strange as I would have thought the other way would have worked. 

 

Here is the working code with full coverage - hopefully someone may find it useful 

 

Trigger

 

trigger OpportunityTrigger on Opportunity (before insert, before update) {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Main Opportunity Trigger
	*/
	
	// Call Opportunity Controller
	OpportunityTriggerHandler handler = new OpportunityTriggerHandler();  
	
	if(Trigger.isInsert && Trigger.isBefore){
		handler.OnBeforeInsert(Trigger.new);

	}
	
	else if (Trigger.isUpdate && Trigger.isBefore){
		handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap); 
	
	}

 	

}

 Class

 

public with sharing class OpportunityTriggerHandler {
	
		/**
		*	@author			Mike Gill
		*	@date			28/07/11
		*	@description	Update account type based on certain criteria
		*/

     
     public OpportunityTriggerHandler(){}
	
	//TODO: Add user custom persmission check
	
	 public void OnBeforeInsert(Opportunity[] newOpps){
	 	
		List<Account> accs = new List<Account>();
		
		 // Create empty set
     	Set<Id> accountIds = new Set<Id>();
		
		// Populate set with updated account ids     	
		for (Opportunity opp:newOpps){
				accountIds.add(opp.AccountId);
		}
		
		// Iterate accounts where type is Lead Acct or Stalled Acct
		for (Account acc: [select Id, Type from Account where (Type = 'Lead Acct' or Type = 'Stalled Acct') and Id IN: accountIds]){
			acc.Type = 'Opportunity Acct';
			accs.add(acc);
			
		}
		
		// Update accounts
		update accs;
	     
     }
     
     public void OnBeforeUpdate(Opportunity[] oldOpps, Opportunity[] updatedOpps, Map<Id, Opportunity> oppMap){
     	
     	// Create list for bulk update of accounts
     	List<Account> accs = new List<Account>();
     	
     	// Create empty set of accounts to be updated
     	Set<Id> accountIds = new Set<Id>();
     	
     	// Iterate updated Opps for related accountids
		for (Opportunity opp:updatedOpps){
			// Add acocunt ids where opportunity is lost
			if (opp.StageName == '8-Closed Lost'){
				accountIds.add(opp.AccountId);
			}
		}
     	
     	
     	for (Account acc:[select Id, Type, Opportunity_Counter__c from Account where (Type = 'Lead Acct' or Type = 'Opportunity Acct') and Opportunity_Counter__c = 1 and Id IN: accountIds ]){
     
     		accs.add( new Account (id=acc.id, Type = 'Stalled Acct' ));
  
     	}
     	
     	update accs;

     	
     }

}

 

Test Class

 

@isTest
private class TestOpportunityTriggerHandler {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Test Scenarios for Opportunity Trigger Handler
	*  	TODO: 			
	*/
	
	static List<Account> accounts;
	
	static List<Opportunity> opps;
	static List<Contact> contacts;
	
	
	
	static { 
			
			// Empty Lists	
			accounts = new List<Account>();
    		opps = new List<Opportunity>();
    		contacts = new List<Contact>();
		
			// Fetch profile id
     		Profile p = [select id from Profile where name = 'Standard User'];
     		
     		// Create user for tetsing
     		User u = new User ( alias = 'testme', email = 'testme@noemail.com', emailencodingkey = 'UTF-8', lastname = 'test',languagelocalekey = 'en_US', 
     		localesidkey = 'en_US', profileid = p.Id, country = 'United Kingdom', timezonesidkey = 'Europe/London', username = 'testme@noemail.com');
     		insert u;
     		
     		// Add  Accounts to the list to be inserted	
     		for (Integer i = 0; i<1; i++){
     			Account a = new Account(
     			Name = 'Test Accts' + i,
     			Type = 'Lead Acct',
     			BillingState = 'CA',
     			Industry = 'Business Services',
     			OwnerId = u.Id
     			);
     			accounts.add(a);
     		}
     		
     			insert accounts;
     	
     		
     		// Add Contacts to the list to be inserted
     		for (Account a: accounts){
     			
     			Contact c = new Contact();
     			c.FirstName = 'Test Contact First';
     			c.LastName = 'Test Contact Last';
     			c.LeadSource = 'Call In';
     			c.AccountId = a.Id;
     			contacts.add(c);
     			
     		}
     		
     		insert contacts;
     		
     
     		
    		
    		for (Account a: accounts){
     			
     			Opportunity o = new Opportunity();
     			o.Name = 'Test Opp';
     			o.AccountId = a.Id;
     			o.CloseDate = Date.today();
     			o.StageName = '1-Qualified Prospect';
     			
     			
     			
     			opps.add(o);
     			
     		}
     	
     
  	
		
	}
	
	
    static testMethod void myUnitTest_CreateOpp() {
    	
    /**
    * @description	Test related account type is set to Opportunity Acct on create of opportunity
    */

			// Start test
			test.startTest();

     		insert opps;
    		
    		// End test
    		test.stopTest();
       		
    }
    
    static testMethod void myUnitTest_UpdateOpportunity(){
    	
    	insert opps;
    	
    	List<Opportunity> oppsToUpdate = new List<Opportunity>();
    	
    	for (Opportunity opp:opps){
    		
    		opp.StageName = '8-Closed Lost';
    		oppsToUpdate.add(opp);
    	}
    	
    	test.startTest();
    	
    	update opps;
    	
    	test.stopTest();
    	
    }
  
}

 

All Answers

markdamomarkdamo

Your OnBeforeInsert function is not running at it has not been called in the OpportunityTriggerHandler class.

MikeGillMikeGill

I have re tweak the test class it's now 90% covered. 

 

Not sure I am instantiating my method correctly in my test class - it's probably something really obvious.

 

Any additonal potinters welcomed.

 

@isTest
private class TestOpportunityTriggerHandler {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Test Scenarios for Opportunity Trigger Handler
	*  	TODO: 			
	*/
	
	static List<Account> accounts;
	//static List<Opportunity> opps;
	static List<Contact> contacts;
	
	
	static {
			
			// Empty Lists	
			accounts = new List<Account>();
    		//opps = new List<Opportunity>();
    		contacts = new List<Contact>();
		
			// Fetch profile id
     		Profile p = [select id from Profile where name = 'Standard User'];
     		
     		// Create user for tetsing
     		User u = new User ( alias = 'testme', email = 'testme@noemail.com', emailencodingkey = 'UTF-8', lastname = 'test',languagelocalekey = 'en_US', 
     		localesidkey = 'en_US', profileid = p.Id, country = 'United Kingdom', timezonesidkey = 'Europe/London', username = 'testme@noemail.com');
     		insert u;
     		
     		// Add  Accounts to the list to be inserted	
     		for (Integer i = 0; i<1; i++){
     			Account a = new Account(
     			Name = 'Test Accts' + i,
     			Type = 'Lead Acct',
     			BillingState = 'CA',
     			Industry = 'Business Services',
     			OwnerId = u.Id
     			);
     			accounts.add(a);
     		}
     		
     			insert accounts;
     	
     		
     		// Add Contacts to the list to be inserted
     		for (Account a: accounts){
     			
     			Contact c = new Contact();
     			c.FirstName = 'Test Contact First';
     			c.LastName = 'Test Contact Last';
     			c.LeadSource = 'Call In';
     			c.AccountId = a.Id;
     			contacts.add(c);
     			
     		}
     		
     		insert contacts;
     	
     
  	
		
	}
	
	
    static testMethod void myUnitTest_CreateOpp() {
    	
    /**
    * @description	Test related account type is set to Opportunity Acct on create of opportunity
    */
    
    		OpportunityTriggerHandler handler = new OpportunityTriggerHandler();
    		
    		List<Opportunity> opps = new List<Opportunity>();
    		
    		for (Account a: accounts){
     			
     			Opportunity o = new Opportunity();
     			o.Name = 'Test Opp';
     			o.AccountId = a.Id;
     			o.CloseDate = Date.today();
     			o.StageName = '1-Qualified Prospect';
     			opps.add(o);
     			
     		}
    		
    		
			handler.OnBeforeInsert( opps );
       	
       		// Check account type is Lead Acct before insert
       		for (Account acc:accounts){
       			System.assertEquals(acc.Type, 'Lead Acct');
       		}	
     	
			
			// Start test
			test.startTest();
			
     		
     		// Insert opps and trigger use case (update account type)

	

     		insert opps;
     		//update opps;
     		
     		System.assert(true);
     		
     	
     		// query for updated accounts (testing..)
     		
     		List<Account> accs = new List<Account>();
     		
     		for (Account acct: [select type from Account where Id in: accounts]){
     			// After trigger executes the account type should be Opportunity Acct (Test Failure...)
  
     			    		System.assertEquals(acct.Type, 'Opportunity Acct');
   			
    		}
    		
    	

    		
    		// End test
    		test.stopTest();
       		
    }
  
}

 

SteveBowerSteveBower

Perhaps I'm missing something, but your OpportunityTriggerHandler class is just that, a *class*, not a trigger.    I think you want to get rid of all this "handler" stuff and declare that class as a Trigger and go from there.   Best, Steve.

MikeGillMikeGill

Thanks Steve for quick response. Still confused as to why I can't hit 100%

 

I am calling this class from a trigger (the trigger is firing as I get the debug message)

 

trigger OpportunityTrigger on Opportunity (before insert, before update) {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Main Opportunity Trigger
	*/
	
	// Call Opportunity Controller
	OpportunityTriggerHandler handler = new OpportunityTriggerHandler();  
	
	if(Trigger.isInsert && Trigger.isBefore){
		handler.OnBeforeInsert(Trigger.new);
		System.debug(Logginglevel.error, 'EB/DEBUG - Trigger code executing...');
	}

 	

}

 

But the test records aren't getting updated.... 

 

All the code I am using is now posted here now.

 

Any more ideas?

SteveBowerSteveBower

 

It's unclear to me why you are calling:  


handler.OnBeforeInsert( opps ); 

 

yourself in the test rather than letting it happen automatically from the Insert call.  You're calling it twice on the same set of records.

 

It's also odd to me that you're creating new Account records, filling in the Id and type and inserting it.   I'd have expected you to query for the Account records you want to change, loop through them setting the new value and then update those.

 

Steve.

 

MikeGillMikeGill

The trigger/class itself is working ok.

 

If you mean here - this is building a list of accounts which require updating after iterating over the opps

 

		for (Opportunity opp:newOpps){
			
			// TODO: Add Apply Sales Process Logic
			if (opp.Type == 'Lead Acct' || opp.Type == 'Stalled Acct'){
				System.debug(Logginglevel.ERROR, 'EB/DEBUG - Class code executing....');
				accs.add( new Account (id=opp.AccountId, Type = 'Opportunity Acct' ));
			}
			
		}
		
		update accs;

 

It sounds like you are saying, I should query for accounts updated instead of like this.

 

Just funny as this works and I would have thought this is the most optimal way. 

 

Thanks for responding.

MikeGillMikeGill

Strange as I would have thought the other way would have worked. 

 

Here is the working code with full coverage - hopefully someone may find it useful 

 

Trigger

 

trigger OpportunityTrigger on Opportunity (before insert, before update) {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Main Opportunity Trigger
	*/
	
	// Call Opportunity Controller
	OpportunityTriggerHandler handler = new OpportunityTriggerHandler();  
	
	if(Trigger.isInsert && Trigger.isBefore){
		handler.OnBeforeInsert(Trigger.new);

	}
	
	else if (Trigger.isUpdate && Trigger.isBefore){
		handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap); 
	
	}

 	

}

 Class

 

public with sharing class OpportunityTriggerHandler {
	
		/**
		*	@author			Mike Gill
		*	@date			28/07/11
		*	@description	Update account type based on certain criteria
		*/

     
     public OpportunityTriggerHandler(){}
	
	//TODO: Add user custom persmission check
	
	 public void OnBeforeInsert(Opportunity[] newOpps){
	 	
		List<Account> accs = new List<Account>();
		
		 // Create empty set
     	Set<Id> accountIds = new Set<Id>();
		
		// Populate set with updated account ids     	
		for (Opportunity opp:newOpps){
				accountIds.add(opp.AccountId);
		}
		
		// Iterate accounts where type is Lead Acct or Stalled Acct
		for (Account acc: [select Id, Type from Account where (Type = 'Lead Acct' or Type = 'Stalled Acct') and Id IN: accountIds]){
			acc.Type = 'Opportunity Acct';
			accs.add(acc);
			
		}
		
		// Update accounts
		update accs;
	     
     }
     
     public void OnBeforeUpdate(Opportunity[] oldOpps, Opportunity[] updatedOpps, Map<Id, Opportunity> oppMap){
     	
     	// Create list for bulk update of accounts
     	List<Account> accs = new List<Account>();
     	
     	// Create empty set of accounts to be updated
     	Set<Id> accountIds = new Set<Id>();
     	
     	// Iterate updated Opps for related accountids
		for (Opportunity opp:updatedOpps){
			// Add acocunt ids where opportunity is lost
			if (opp.StageName == '8-Closed Lost'){
				accountIds.add(opp.AccountId);
			}
		}
     	
     	
     	for (Account acc:[select Id, Type, Opportunity_Counter__c from Account where (Type = 'Lead Acct' or Type = 'Opportunity Acct') and Opportunity_Counter__c = 1 and Id IN: accountIds ]){
     
     		accs.add( new Account (id=acc.id, Type = 'Stalled Acct' ));
  
     	}
     	
     	update accs;

     	
     }

}

 

Test Class

 

@isTest
private class TestOpportunityTriggerHandler {
	
	/**
	*	@author			Mike Gill
	*	@date			28/07/11
	*	@description	Test Scenarios for Opportunity Trigger Handler
	*  	TODO: 			
	*/
	
	static List<Account> accounts;
	
	static List<Opportunity> opps;
	static List<Contact> contacts;
	
	
	
	static { 
			
			// Empty Lists	
			accounts = new List<Account>();
    		opps = new List<Opportunity>();
    		contacts = new List<Contact>();
		
			// Fetch profile id
     		Profile p = [select id from Profile where name = 'Standard User'];
     		
     		// Create user for tetsing
     		User u = new User ( alias = 'testme', email = 'testme@noemail.com', emailencodingkey = 'UTF-8', lastname = 'test',languagelocalekey = 'en_US', 
     		localesidkey = 'en_US', profileid = p.Id, country = 'United Kingdom', timezonesidkey = 'Europe/London', username = 'testme@noemail.com');
     		insert u;
     		
     		// Add  Accounts to the list to be inserted	
     		for (Integer i = 0; i<1; i++){
     			Account a = new Account(
     			Name = 'Test Accts' + i,
     			Type = 'Lead Acct',
     			BillingState = 'CA',
     			Industry = 'Business Services',
     			OwnerId = u.Id
     			);
     			accounts.add(a);
     		}
     		
     			insert accounts;
     	
     		
     		// Add Contacts to the list to be inserted
     		for (Account a: accounts){
     			
     			Contact c = new Contact();
     			c.FirstName = 'Test Contact First';
     			c.LastName = 'Test Contact Last';
     			c.LeadSource = 'Call In';
     			c.AccountId = a.Id;
     			contacts.add(c);
     			
     		}
     		
     		insert contacts;
     		
     
     		
    		
    		for (Account a: accounts){
     			
     			Opportunity o = new Opportunity();
     			o.Name = 'Test Opp';
     			o.AccountId = a.Id;
     			o.CloseDate = Date.today();
     			o.StageName = '1-Qualified Prospect';
     			
     			
     			
     			opps.add(o);
     			
     		}
     	
     
  	
		
	}
	
	
    static testMethod void myUnitTest_CreateOpp() {
    	
    /**
    * @description	Test related account type is set to Opportunity Acct on create of opportunity
    */

			// Start test
			test.startTest();

     		insert opps;
    		
    		// End test
    		test.stopTest();
       		
    }
    
    static testMethod void myUnitTest_UpdateOpportunity(){
    	
    	insert opps;
    	
    	List<Opportunity> oppsToUpdate = new List<Opportunity>();
    	
    	for (Opportunity opp:opps){
    		
    		opp.StageName = '8-Closed Lost';
    		oppsToUpdate.add(opp);
    	}
    	
    	test.startTest();
    	
    	update opps;
    	
    	test.stopTest();
    	
    }
  
}

 

This was selected as the best answer