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
VamsiVamsi 

how to cover apexpages.addmessage in test class

Hi ,

Can someone please help me to cover the below 2 lines in catch block in my contoller class 

  Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
I have used the below code in my class but its entering the catch block while testing, but not sure how to cover those lines.
if(Test.isRunningTest())
              integer intt = 10/0;

Apex class 

public with sharing class mycasecom {

    public String test2 { get; set; }
    public String test1 { get; set; }
    public string test3 {get;set;}
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID ID ;
       
     public void save() 
     {
     
     id = ApexPages.currentPage().getParameters().get('caseid');
     system.debug('case id entered' + ID);
      ca = new casecomment();
      ca.ParentId= id;
      ca.commentbody = test1 + '\n' + test2 + '\n' + test3;
      ca.IsPublished = true;
      list<case> c = [select Status from case where ID=:ID];
      list<case> cc = new list<case>();
      for(case cd : c)
      {
          cd.Status = 'Closed';
          cc.add(cd);
      }
      try {
             insert ca;
              update cc;
           status = 'saved';
         system.debug('status value'+ status);
       
          if(Test.isRunningTest())
              integer intt = 10/0;
       }catch(DmlException d)
      {
       Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
      }

}
}

Test Class 

@isTest
public class PopupTestClass 
{
    @isTest public static void withcaseid()
    {
        
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        case ca = [select id, status from case where status = 'New'];
        pagereference p = page.casecomment;
        test.setCurrentPage(p);
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
   
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        cs.save();
        
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = cs.test1 +'\n'+ cs.test2 +'\n' +cs.test3;
        system.assertEquals(str , cm.CommentBody);
        system.assert(true, cm.ispublished);
        case g = [select Status from case where ID =: ca.Id];
        system.assertEquals('Closed', g.status);
        
        
            }
    
    @isTest static void withoutcaseid()
    {
        
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        pagereference p = page.casecomment;
        test.setCurrentPage(p);
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
       
        apexpages.currentPage().getparameters().put('caseid', null);
        cs.save();
       
        system.assertEquals('unsaved', cs.status);
        
   }
}
Best Answer chosen by Vamsi
N.M. SharmaN.M. Sharma
Hey Vamshi 

I have found there is some issue in your main controller i have fixed those plase try both. Test class also cover 100% code coverage 

Controller: 
public with sharing class mycasecom {

    public String test2 { get; set; }
    public String test1 { get; set; }
    public string test3 {get;set;}
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID ID ;
       
     public void save(){
        id = ApexPages.currentPage().getParameters().get('caseid');
        system.debug('case id entered' + ID);
        ca = new casecomment();
        ca.ParentId= id;
        ca.commentbody = test1 + '\n' + test2 + '\n' + test3;
        ca.IsPublished = true;
        list<case> c = [select Status from case where ID=:ID];
        list<case> cc = new list<case>();
        for(case cd : c){
            cd.Status = 'Closed';
            cc.add(cd);
        }
        try {
            insert ca;
            update cc;
            status = 'saved';
            system.debug('status value'+ status);
        }catch(DmlException d){
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
        }
    }
}

Test Class
@isTest
public class PopupTestClass {
    @isTest public static void withcaseid(){
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        case ca = [select id, status from case where status = 'New'];
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
   
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        cs.save();
        
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = cs.test1 +'\n'+ cs.test2 +'\n' +cs.test3;
        system.assertEquals(str , cm.CommentBody);
        system.assert(true, cm.ispublished);
        
        case g = [select Status from case where ID =: ca.Id];
        system.assertEquals('Closed', g.status);
        
    }
    
    @isTest static void withoutcaseid(){
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
        apexpages.currentPage().getparameters().put('caseid', null);
        cs.save();
    }
}

Cheers :)

All Answers

Vasani ParthVasani Parth
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.
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);

Please mark this as the best answer if this helps
N.M. SharmaN.M. Sharma
Hi Vamshi,

For cover catch part just miss any required field in Case or in CaseCommet. So when it going to update in Try the exception occure and your catch (add message part) is automatically covered :)

Cheers
VamsiVamsi
Hi Vasani Parth,

Thank you for the quick response. when i add the above code to my testclass , it throws me an error System.MathException: Divide by 0.

withcaseID test method has been failed.

list<apexpages.Message> am = new list<apexpages.Message>();
        system.assertNotEquals(0, am.size());
        Boolean messageFound = false;
        for(apexpages.Message msg : am)
        {
            if(msg.getDetail() =='missing required field:[ParentId]'&& msg.getSeverity() == ApexPages.Severity.Error)    
            messageFound = true;
        }
        system.assert(messageFound);       
N.M. SharmaN.M. Sharma
Hey Vamshi 

I have found there is some issue in your main controller i have fixed those plase try both. Test class also cover 100% code coverage 

Controller: 
public with sharing class mycasecom {

    public String test2 { get; set; }
    public String test1 { get; set; }
    public string test3 {get;set;}
    public string status {get;set;}
    public casecomment ca;
    public case c ;
    public ID ID ;
       
     public void save(){
        id = ApexPages.currentPage().getParameters().get('caseid');
        system.debug('case id entered' + ID);
        ca = new casecomment();
        ca.ParentId= id;
        ca.commentbody = test1 + '\n' + test2 + '\n' + test3;
        ca.IsPublished = true;
        list<case> c = [select Status from case where ID=:ID];
        list<case> cc = new list<case>();
        for(case cd : c){
            cd.Status = 'Closed';
            cc.add(cd);
        }
        try {
            insert ca;
            update cc;
            status = 'saved';
            system.debug('status value'+ status);
        }catch(DmlException d){
            Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage())) ;
            status = 'unsaved';
        }
    }
}

Test Class
@isTest
public class PopupTestClass {
    @isTest public static void withcaseid(){
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        case ca = [select id, status from case where status = 'New'];
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
   
        apexpages.currentPage().getparameters().put('caseid', ca.id);
        cs.save();
        
        casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];
        string str = cs.test1 +'\n'+ cs.test2 +'\n' +cs.test3;
        system.assertEquals(str , cm.CommentBody);
        system.assert(true, cm.ispublished);
        
        case g = [select Status from case where ID =: ca.Id];
        system.assertEquals('Closed', g.status);
        
    }
    
    @isTest static void withoutcaseid(){
        case c = new case(status = 'New',Origin = 'Phone');
        insert c;
        mycasecom cs = new mycasecom();
        cs.Test2=('test1');
        cs.Test1=('test2');
        cs.Test3=('test3');
        apexpages.currentPage().getparameters().put('caseid', null);
        cs.save();
    }
}

Cheers :)
This was selected as the best answer
VamsiVamsi
Thank you Sharma. Now I get 100 % code coverage.

I could see you have removed the below code from my class

if(Test.isRunningTest())
              integer intt = 10/0;

even before i have tried removing those lines, test class methods have passed but it shows the code coverage as 88%. 

Could you please let me know the changes that you had made to the testclass or controller class 
 
N.M. SharmaN.M. Sharma
:)