+ Start a Discussion

ApexPages.addMessage throws Exception in Test Methods


When writing test methods for visualforce page extensions, if there's a section of code inside the extension that creates an error message like the following:

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'Custom Error Message'));

Then salesforce throws the following exception:

System.Exception: ApexPages.addMessage can only be called from a Visualforce page, for now I'm getting arround it by wrapping it in a try catch and asserting that the error message is the expected one for ApexPages.addMessage, but I think it should be able to be called during a test.

This is a known issue and we have already logged a bug on it.
Thanks Jill,

Is there a public place to view acknowledge reported bugs?

Scott says he wrapped the test code that causes the controller to call ApexPages.addMessage in a try/catch block. I just tried to do that, but it doesn't seem to be catching the exception. When I run the test code below, the controller throws the expected exception, but the catch block doesn't catch it.

TestController myController = new TestController();
try {
    System.debug('About to do save.');
    String newPage = myController.save().getUrl();
    System.debug('Done with save.');
catch (System.Exception ex) {
    System.debug('Caught exception' + ex.getMessage());
    System.assertEquals('ApexPages.addMessage can only be called from a Visualforce page',

Granted, I'm pretty new at  Apex and VisualForce, so it's probably a newbie problem. Any ideas?

Thank you,


Dogen ZenjiDogen Zenji
Hi Jeri.  Have you figured out how to catch the addMessage exception as Scott suggested?  I would love to trap this error because not doing so prevents me from getting 75% code coverage so any help would be greatly appreciated.  Salesforce, any word on the release schedule for this bug fix?
Nope, I haven't figured out how to catch it, and I haven't heard a peep about it.
I'd like to report it somewhere as a problem, but I don't know where. Any pointers, anyone?
We currently do not have public access to our issues.  For this issue please contact salesforce.com support and log a case. When you do give them the bug #190932. This will help us get it prioritized for a patch release.

This should be fixed for most instances now.
Looks fixed to me!
Thank you!