Sample Apex Unit Test for Apex Trigger

Today I received an inquiry from a Salesforce administrator who read an article about using an Apex Trigger to reassign Contacts and Opportunities when Account reassignments happen outside of the standard Salesforce User Interface. She was encountering issues deploying the code. For some reason I failed to include any Apex Test class in that original post.

Since I was going to help her out I decided that this would be another decent example for other readers. It certainly can't hurt to have another Apex Unit Test sample to assist others learning Apex. Plus it gives me more content for this site...

So here's an Apex Test Method example that actually provide 96% code coverage for the original Account trigger I wrote. The test doesn't cover the one line after the catch statement of the trigger. So if you drop the try/catch logic from that trigger you will get 100% coverage using the test method provided below.

/*
	Created by: Greg Hacic
	Last Update: 25 March 2014 by Greg Hacic
	Questions?: greg@interactiveties.com
	
	NOTES:
		- Tests the reassignRelatedContactsAndOpportunities trigger
		- Provides 96% coverage (validates everything except the catch portion of the logic in the trigger)
*/
@isTest
private class reassignmentTriggerTEST {
	
	//test for account update being made by incorrect user
	@isTest //defines method for use during testing only
	static void someContactsAndOpportunities() {
	//BEGIN: perform some setup steps...
		//create some testing accounts
		List<Account> accounts = new List<Account>();
		accounts.add(new Account(Name = 'Interactive Ties', Website = 'http://www.interactiveties.com/'));
		insert accounts; //insert the account list
		//create some testing contacts
		List<Contact> contacts = new List<Contact>();
		contacts.add(new Contact(AccountId = accounts[0].Id, FirstName = 'Tess', LastName = 'Dachshund', email='tess@ities.co')); //new Contact detail
		contacts.add(new Contact(AccountId = accounts[0].Id, FirstName = 'Grachus', LastName = 'Dachshund', email='grachus@ities.co')); //another new Contact detail
		insert contacts; //insert the contact list
		//create some testing opportunities
		List<Opportunity> opportunities = new List<Opportunity>();
		opportunities.add(new Opportunity(AccountId = accounts[0].Id, Amount = 20000, CloseDate = date.today(), Name = 'Test Opportunity', StageName = 'Identified'));
		opportunities.add(new Opportunity(AccountId = accounts[0].Id, Amount = 10000, CloseDate = date.today(), Name = 'Test Opportunity', StageName = 'Identified'));
		insert opportunities; //insert the opportunity list
		Profile prof = [SELECT Id FROM Profile WHERE Name = 'System Administrator']; //get a profile Id
		User user = new User(Alias = 'TDemo', Email = 'greg@interactiveties.com', EmailEncodingKey = 'ISO-8859-1', FirstName = 'Demo', LanguageLocaleKey = 'en_US', LastName = 'User', LocaleSidKey = 'en_US', ProfileId = prof.Id, TimeZoneSidKey = 'America/Denver', Username = 'demo.test.user@interactiveties.com'); //new User details
		insert user;
	//END: perform some setup steps...
		Test.startTest();
		//reassign the account
		List<Account> accountUpdates = new List<Account>(); //new List of Account sObjects
		accountUpdates.add(new Account(Id = accounts[0].Id, OwnerId = user.Id));
		update accountUpdates;
		Test.stopTest();
		//validate that the account is assigned properly
		Account a = [SELECT OwnerId FROM Account WHERE Id =: accounts[0].Id];
		System.assertEquals(a.OwnerId, user.Id);
		//validate that the contacts are assigned properly
		for (Contact c : [SELECT OwnerId FROM Contact WHERE AccountId =: accounts[0].Id]) {
			System.assertEquals(c.OwnerId, user.Id);
		}
		//validate that the opportunities are assigned properly
		for (Opportunity o : [SELECT OwnerId FROM Opportunity WHERE AccountId =: accounts[0].Id]) {
			System.assertEquals(o.OwnerId, user.Id);
		}
	}

}

I commented the code in order to address what each line is doing but feel free to email me with questions.

Also, thanks to Quené for reaching out to me. I'm glad that others are reading the information I put out here and I appreciate the feedback.

Automated Exchange Rates in Salesforce.com

Reduce Repetitive Tasks, Eliminate Errors & Free Up Your Administrators.

Birthday Reminders for Salesforce.com

It might lead to a sale. Or it might make you feel good.