function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Walter@AdicioWalter@Adicio 

How do I test a specific page message was added?

i am having trouble finding examples to test something like this...

 

	 	if ( searchStr.length() < 2 ) {
	 		ApexPages.addMessage( new ApexPages.Message(
	 			ApexPages.Severity.INFO, 'Search requires more characters'));
	 		return null;
	 	}

 

thank you.

Best Answer chosen by Admin (Salesforce Developers) 
jhenningjhenning

How about this:

 

 

List<Apexpages.Message> msgs = ApexPages.getMessages();
boolean b = false;
for(Apexpages.Message msg:msgs){
    if (msg.getDetail().contains('Search requires more characters')) b = true;
}
system.assert(b);

 

 

All Answers

jhenningjhenning

How about this:

 

 

List<Apexpages.Message> msgs = ApexPages.getMessages();
boolean b = false;
for(Apexpages.Message msg:msgs){
    if (msg.getDetail().contains('Search requires more characters')) b = true;
}
system.assert(b);

 

 

This was selected as the best answer
Tim__mTim__m

In a unit test you would do it like so

 

 

PageReference pageRef = Page.MyPage;
// add your parameters if you use any
pageRef.getParameters().put('retURL','http://example.org');
// tell the testing framwork what page is the currentpage
Test.setCurrentPage(pageRef);
		
MyPageController controller = new MyPageController();
// call the method in your controller that you want to test
controller.save();
// get the list of ApexPages.Message
List<ApexPages.Message> msgList = ApexPages.getMessages();
// or loop over the messages
for(ApexPages.Message msg :  ApexPages.getMessages()) {
    System.assertEquals('Have a nice day', msg.getSummary());
    System.assertEquals(ApexPages.Severity.ERROR, msg.getSeverity()); 
}

 

Walter@AdicioWalter@Adicio

yes these work. thank you! jhenning and Tim__m i have a much better understanding now.

c_jonasc_jonas

IMO, a better way would be to have your page message declared as a constant in the controller class.  
@testvisible
private static final String MSG_SEARCH_ERROR = 'Search requires more characters';

Then in your test method you can refrence it directly:
 
boolean msgFound = false; 
for(Apexpages.Message msg : ApexPages.getMessages()){ 
      if (msg.getDetail() == MyController.MSG_SEARCH_ERROR) msgFound = true; 
} 
system.assert(msgFound);

This way if your error message needs changes at some point, you only need to update it in one place.
Oleksandr VlasenkoOleksandr Vlasenko
private static Boolean checkApexMessages(String message) {
    for(Apexpages.Message msg : ApexPages.getMessages()){
        if (msg.getDetail().contains(message)) {
            return true;
		}
    }
	return false;
}
Might be better
MUSTAPHA ELMADIMUSTAPHA ELMADI
Thanks @jhenning, i used msg.getSummary(), containts.(labelMsg) and a label for the message. and it works.