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
Anoop Patel 11Anoop Patel 11 

Controller Method Not Being Called in Test Class

My test class returns 'System.NullPointerException: Attempt to de-reference a null object' when I uncomment the highlights reference to my method? If I comment then it runs but only covers 60%.

Controller
public List<EventRelation> getParticipants(){
        
        List<EventRelation> inviteeRelations = new List<EventRelation>();
    
        if(mt.Id!=null){
            inviteeRelations = new List<EventRelation>([SELECT Id, Relation.Name FROM EventRelation 
                                WHERE EventId =:mt.Id 
                                AND IsWhat = false]); 
        }
        return inviteeRelations ;

Test Class

 Test.startTest();  
      
           System.runAs(u) {  
               ApexPages.StandardController controller = new APexPages.StandardController(event);
               CORE_viewEventWordController extension = new CORE_viewEventWordController(controller);
               String url=extension.getmyimageurl();             
               //List<EventRelation> listPart=extension.getParticipants();
               us=extension.eventOwner;
           }
       Test.stopTest();    }
 
Best Answer chosen by Anoop Patel 11
James LoghryJames Loghry
No... Your constructor should be updated to the following:
 
public CORE_viewEventWordController(ApexPages.StandardController stdController) {    
    eventId= stdController.getId();
}

 

All Answers

Vishnu VaishnavVishnu Vaishnav
your code little bit wrong :

public List<EventRelation> getParticipants(){
        
        List<EventRelation> inviteeRelations = new List<EventRelation>();
    
        if( mt != null ){ // You are usin mt.id that means if mt is null than it work like null.id 
            inviteeRelations = new List<EventRelation>([SELECT Id, Relation.Name FROM EventRelation 
                                WHERE EventId =:mt.Id 
                                AND IsWhat = false]); 
        }
        return inviteeRelations ;
}

I hope u got the solution..
 
MithunPMithunP
Hi Anoop,

Update     //List<EventRelation> listPart=extension.getParticipants(); as extension.getParticipants();

Below is updated code
 Test.startTest();  
      
           System.runAs(u) {  
               ApexPages.StandardController controller = new APexPages.StandardController(event);
               CORE_viewEventWordController extension = new CORE_viewEventWordController(controller);
               String url=extension.getmyimageurl();             
              extension.getParticipants();
               us=extension.eventOwner;
           }
       Test.stopTest();    }

Best Regards,
Mithun.
James LoghryJames Loghry
Mithun,

Without seeing the rest of your controller, it appears the "mt" variable in your method is what is causing the NullPointerException.  Make sure that mt is populated.  Furthermore, your method queries for the EventRelation object.  You'll need to create all of these records in your unit tests before you execute the code, in order for your test to succeed.
Anoop Patel 11Anoop Patel 11
This is the complete controller;

public class CORE_viewEventWordController {
   
    public Event mt{
        get{
            if(mt==null && eventId!=null)
            {
                try{
                    mt=[Select id,OwnerId,WhatId,ActivityDate,ActivityDateTime,Subject,Description,Location,Summary__c From Event WHERE IsDeleted = false AND id=:eventId LIMIT 1 ALL ROWS];
                }catch(Exception e){}
            }
            
            return mt;
        }
        set;
    }
    
    public User eventOwner{
        get{
            if(eventOwner==null && mt!=null && mt.OwnerId!=null )
            {
                try{
                    eventOwner=[Select id,Name From User where id=:mt.OwnerId LIMIT 1];
                }catch(Exception e){}
            }
            
            return eventOwner;
        }
        set;
    }
    
    Id eventId;
    
    public CORE_viewEventWordController(ApexPages.StandardController stdController) {        
        eventId=(Id)System.currentPageReference().getParameters().get('id');
        //((Event)stdController.getRecord()).id;
        
    }
    
    public String getmyimageurl () {
        string imageid='';
        try{ 
            Document dc = [Select id from Document where Name = 'LCHLogo' LIMIT 1];
            imageid = String.valueof(dc.id).substring(0,15);
        }catch(Exception e){}
        
        String orgId = UserInfo.getOrganizationId();
        String domain= ApexPages.currentPage().getHeaders().get('Host') ;
        
        return 'http://'+domain+'/servlet/servlet.ImageServer?id='+imageid +'&oid='+orgId;
    }
    
    public List<EventRelation> getParticipants(){
        
        List<EventRelation> inviteeRelations = new List<EventRelation>();
    
        if(mt.Id!=null){
            inviteeRelations = new List<EventRelation>([SELECT Id, Relation.Name FROM EventRelation 
                                WHERE EventId =:mt.Id 
                                AND IsWhat = false]); 
        }

        return inviteeRelations ;
    }
}

This is complete test;
@isTest
private class CORE_viewEventWordControllerTest {

    static User u;
    static Contact contact;
    static Account acc;
   
    static{
   
        // create a user to run the test as
        Profile p = [select id from profile where name='System Administrator'];
        u = new User(alias = 'test456', email='test456@noemail.com',
            emailencodingkey='UTF-8', lastname='Testing2', languagelocalekey='en_US',
            localesidkey='en_US', profileid = p.Id, country='United States',
            timezonesidkey='America/Los_Angeles', username='test456@noemail.com');
        insert u;
       
        contact = new Contact(Phone='+34987888888',LastName='lastnametest');
        acc= new Account(Name='TestAcc');

    }
   
    @isTest (SeeAllData=true) static void findsDocument() {
       performTest();
    }
   
    @isTest static void doesNoTFindDocument() {
       performTest();
    }
   
    static void performTest(){
      
       User us;
      
       System.runAs(u) {
            insert contact;
            insert acc;
       }

       Event event=new Event(DurationInMinutes=10,ActivityDateTime=datetime.now(),WhoId=contact.id,whatId=acc.id);

       System.runAs(u) {
            insert event;
       }
      
       Test.startTest();  
      
           System.runAs(u) {  
               ApexPages.StandardController controller = new APexPages.StandardController(event);
               CORE_viewEventWordController extension = new CORE_viewEventWordController(controller);
               String url=extension.getmyimageurl();             
               //List<EventRelation> listPart=extension.getParticipants();
               us=extension.eventOwner;
           }
          
       Test.stopTest();    }
}
James LoghryJames Loghry

Your test is looking for an http parameter of "id".  Either you need to specify this http parameter in your test class, or you need to upate your constructor to look for the id using the standard controller like so:

eventId = stdController.getId();

Also, personally, I hate the getters where you check if it doesn't exist, then you fetch it.  This is typically only relevant in a singleton pattern.  Why not simply query for the object or initialize it in your constructor?
Anoop Patel 11Anoop Patel 11
Sorry James do you mean changing this part in the test class?

String url=extension.getmyimageurl(); 

and should it look like this;

eventId = stdController.getId();
James LoghryJames Loghry
No... Your constructor should be updated to the following:
 
public CORE_viewEventWordController(ApexPages.StandardController stdController) {    
    eventId= stdController.getId();
}

 
This was selected as the best answer
Anoop Patel 11Anoop Patel 11
Thanks James et all,

Once I changed this in my controller it worked and came back with 93% coverage.

Thanks again.