ApexPages.addMessage() behavior inconsistent by version

While converting a utility class from V26 to V31, my VF testmethods started breaking.

Problem was traced down to how ApexPages.addMessage() behavior varies if the i+1st message has the same summary as the ith message, even if the detail argument is different between i+1st and ith message.

If the summary values are the same, the i+1st message won’t get added to the page messages.

Here is the code that proves this:

@isTest
private static void testAddVFMsg() {    
    Test.startTest();
    Test.setCurrentPage(Page.Foo);
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'MsgSummary','00detail'));
    System.assertEquals(1,ApexPages.getMessages().size());

    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'MsgSummary','01detail'));
     // passes at V28 and earlier, fails at V29+
    System.assertEquals(2,ApexPages.getMessages().size()); 

    Test.stopTest();
}

Obviously I can work around this by using different values for the summary argument in the ApexPages.Message constructor or reworking my testmethod expectations.

But – seems to me that if you call addMessage(..), the resulting getMessages() should include the message you added.

So – the question is:

  • Bug? or
  • Documentation needs enhancing?

Answer

I have personally run into several problems using apex page messages – everything from messages not showing up, to ui breaking on different browsers and everything in between.

personally I prefer to approach error handling with a simple Boolean and String. In the case of an error you simply set the Boolean to true (set to false in constructor) and write an error message in the string.

If you are wishing to view this on a VF page you can simply add an outputPanel

<apex:outputPanel id="errorArea"> 
<apex:outputPanel rendered="{!error}">  
<apex:outputText value="{!errorMsg}" /> 
</apex:outputPanel> 
</apex:outputPanel>

Where error is the Boolean and errorMsg is the String. At the beginning of each class simply set the boolean to false and to true again if another error occurs.

This way you have complete control over the message handling, the level of detailing in your debug as well as presentation on the VF page.

Attribution
Source : Link , Question Author : cropredy , Answer Author : David Dawson

Leave a Comment