How to test page messages in unit test?
You can use ApexPages.getMessages()
within your test to get the page messages for the current context, then check that array to make sure that it contains the error message that you're expecting.
ApexPages.Message[] pageMessages = ApexPages.getMessages();
System.assertNotEquals(0, pageMessages.size());
// Check that the error message you are expecting is in pageMessages
Boolean messageFound = false;
for(ApexPages.Message message : pageMessages) {
if(message.getSummary() == 'Your summary'
&& message.getDetail() == 'Your detail'
&& message.getSeverity() == ApexPages.Severity.YOUR_SEVERITY) {
messageFound = true;
}
}
System.assert(messageFound);
This is the pattern I tend to use, even for single messages, as it can easily be adapted to check for multiple messages whilst not caring about what order they are added to the page.
Alternatively you can factor it out into a helper method:
private static Boolean wasMessageAdded(ApexPages.Message message) {
Boolean messageFound = false;
for(ApexPages.Message msg : pageMessages) {
if(msg.getSummary() == message.getSummary()
&& msg.getDetail() == message.getDetail()
&& msg.getSeverity() == message.getSeverity()) {
messageFound = true;
}
}
return messageFound;
}
Then use it as follows:
System.assert(wasMessageAdded(new ApexPages.Message('Your validation message here...')));
Try something like this:
PageReference pageRef = Page.unsubscribePage; //new page reference
pageRef.getParameters().put('x', 'y'); //set additional paramethers
Test.setCurrentPage(pageRef); // set as current page
// your test logic
List<Apexpages.Message> pageMessages = ApexPages.getMessages();