Testing Controllers in Salesforce
Posted in Programming-Platforms, Salesforce, Software Development, Software Maintenance
Just a quick blog today to address an issue that I have been encountered several times since I began programming in Apex, the proprietary language for Salesforce.com. Some developers have become frustrated when trying to write unit tests for their Controllers. To be fair, if you don’t know what base you assertions on, it can be hard to test the code. So here are a couple of quick tips for getting it done:
Imaging you have a controller like the following:
public class SomeController {
public SomeController (ApexPages.StandardController controller) {
if (System.currentPageReference().getParameters().
get(’someParam’)!= null {
ApexPages.addMessage(new ApexPages.Message
(ApexPages.Severity.CONFIRM, ‘Parameter Exists’));
} else if (System.currentPageReference().
getParameters().get(’update’)!= null) {
ApexPages.addMessage(new ApexPages.Message
(ApexPages.Severity.ERROR,
’Parameter Does Not Exist’));
}
}
}
Appropriate tests might look like the following:
static testMethod void testConstructorParameters_noParams() {
PageReference ref =
new PageReference(’/apex/yourVisualforcePage’);
Test.setCurrentPage(ref);
SomeController controller = new SomeController (null);
System.assert
(ApexPages.getMessages().size() == 1);
System.assert
(ApexPages.getMessages().get(0).getDetail()
== ‘Parameter Does Not Exist’);
System.assert
(ApexPages.getMessages().get(0).getSeverity()
== ApexPages.Severity.ERROR);
}
static testMethod void testConstructorParameters_paramExists() {
PageReference ref =
new PageReference(’/apex/yourVisualforcePage?someParam=xyz’);
Test.setCurrentPage(ref);
SomeController controller = new SomeController (null);
System.assert
(ApexPages.getMessages().size() == 1);
System.assert
(ApexPages.getMessages().get(0).getDetail()
== ‘Parameter Exists’);
System.assert
(ApexPages.getMessages().get(0).getSeverity()
== ApexPages.Severity.CONFIRM);
}
The trick here is to use the Test.setCurrentPage() method to let the testing context know what PageReference it is working with. Then you can simply create a new Controller with a null argument, and check the messages manually. If you are testing a method that returns a PageReference, you set up the parameters in the same way, and then run your assertions against the PageReference to verify that all of the pertinent data has been set.
static testMethod void testCreateLink() {
SomeController controller = new SomeController (null);
System.assert(ApexPages.getMessages().size() == 0);
PageReference ref
= new PageReference(’/apex/yourVisualforcePage?someParam=xyz’);
Test.setCurrentPage(ref);
PageReference ref = controller.createLink();
System.assert(ref.getUrl() == ‘/apex/someUrl’);
}
Happy Testing!
Don't miss any posts! Subscribe to our blog feed or only posts by Paul Bourdeaux.
Short URL: http://sundoginteractive.com/e/3100


Comments
Be the first to comment!
Leave A Comment