+ Start a Discussion
Alex D 10Alex D 10 

test class coverage & resolving apex test errors

Hey all, 

Having some issues with writing a test class. My coverage overall is only 47% and I'm also getting some Apex Test failures I need to address. Any guidance would be greatly appreciated. 

Apex Class:
public class SessionMemberTriggerHandler implements ITrigger{
    public SessionMemberTriggerHandler(){}
    public void bulkBefore(){
        updateSessionMember();
    }
    public void bulkAfter(){    
    }
    public void beforeInsert(){}
    public void beforeUpdate(){}
    public void beforeDelete(){}
    public void afterInsert(){}
    public void afterUpdate(){}
    public void afterDelete(){}
    public void afterUnDelete(){}
    public void andFinally(){}
    
/*------------------service methods--------------------*/
    public static void updateSessionMember(){
        try{
        
        Set<id> sessionId=new Set<Id>();
        
       
        Set<id> contactIds =new Set<Id>();
        for(Session_Member__c sm:(List<Session_Member__c>)trigger.new){
            sessionId.add(sm.Session__c);
            contactIds.add(sm.Contact__c);
        }
        
        //system.assert(false, '12121221'+contactIds);
 /*-----------------------------------------Decision-----------------------------------------------------------------*/       
        Map<Id,Session__c> sessionMap=new Map<Id,Session__c>();
        Set<Id> campId=new Set<Id>();
        
        Map<Id,Integer> mapSessionMembers =new Map<Id,Integer>();
        
        for(Session__c s:[select id,Start__c,end__c,Campaign__c,Participant_Capacity__c,(select id from Session_Attendees__r) from Session__c where id in: sessionId]){
            sessionMap.put(s.id,s);
            campId.add(s.Campaign__c);
            mapSessionMembers.put(s.id,0);
            if(s.Session_Attendees__r.size()>0){
                mapSessionMembers.put(s.id,s.Session_Attendees__r.size());
            } 
        }
        Map<Id,Session__C> SessionMap2=new Map<Id,Session__c>([select id,Start__c,end__c,Campaign__c,Participant_Capacity__c from Session__c where Campaign__c in: campId]);
        
        
        Map<Id,List<Session__c>> mapContactSessions =new Map<Id,List<Session__c>>();
        
        
        
        for (Session_Member__c sm:  [select id,Session__c, contact__c from Session_Member__c where contact__c in : contactIds
         and Session__r.campaign__c in: campId ]) {
             
            if(!mapContactSessions.containsKey(sm.contact__c)){
                mapContactSessions.put(sm.contact__c,new List<Session__C>());
            }
            mapContactSessions.get(sm.contact__c).add(SessionMap2.get(sm.Session__c));
            
        }
        
        /*
        for(Session__c ses:[select id,Start__c,Campaign__c,end__c,
            (select id,contact__c from Session_Attendees__r where contact__c in : contactIds) from Session__c
             where campaign__c in:campId]){
            
            if(!sessionMap.containsKey(ses.id)){
                sessionMap.put(ses.id,ses);
            }
            for(Session_Member__c sm:ses.Session_Attendees__r){
                if(!mapContactSessions.containsKey(sm.contact__c)){
                    mapContactSessions.put(sm.contact__c,new List<Session__C>());
                }
                mapContactSessions.get(sm.contact__c).add(ses);
            }
        }*/
        
        
        Map<string,integer> sessioMCounter=new Map<String,integer>();
        
        //100
        for(Session_Member__c sm:(List<Session_Member__c>)trigger.new){
            if(!sm.triggerApply__c && sm.Status__c!='Attended'){
                if(sm.contact__c != null){
                   //  sm.status__c= getSeesionMemberStatus(sm.contact__c,sessionMap.get(sm.session__c),contSet);
                    Session__c session = sessionMap.get(sm.session__c);
                    //integer participantCapacity = session.Participant_Capacity__c;
                    //integer sessionMembersCount = session.Session_Attendees__r.size() ;
                    System.debug('============mapContactSessions.containsKey(sm.contact__c)============='+mapContactSessions.containsKey(sm.contact__c));
                    if(mapContactSessions.containsKey(sm.contact__c)){
                        // 5
                        for(Session__c existingSession: mapContactSessions.get(sm.contact__c)){
                            // existing 2 - 4 -  
                            // current session 1 - 2
                            /*
                            System.debug('===session.start__c==='+session.start__c);
                            System.debug('===existingSession.start__c==='+existingSession.start__c);
                            System.debug('===session.end__c ==='+session.end__c );
                            System.debug('===existingSession.end__c ==='+existingSession.end__c );
                            
                            System.debug('===session.start__c > existingSession.start__c==='+(session.start__c > existingSession.start__c));
                            System.debug('===session.start__c < existingSession.end__c==='+(session.start__c < existingSession.end__c));
                            System.debug('===session.end__c > existingSession.start__c==='+(session.end__c > existingSession.start__c));
                            System.debug('===session.end__c < existingSession.end__c==='+(session.end__c < existingSession.end__c));
                            */
                            
                            
                            
                            if((session.start__c > existingSession.start__c && session.start__c < existingSession.end__c)
                             ||(session.end__c > existingSession.start__c && session.end__c < existingSession.end__c)
                             || (session.start__c == existingSession.start__c)
                            ){
                                sm.Status__c ='Registered-DB';
                                break;
                            }
                            else {
                                sm.Status__c ='Registered' ;
                            }
                            
                            
                            //system.assert(false, durationInMin +'####'+ duration + '####' + sm.Status__c +'####'+(durationInMin > duration));
                        }
                    } 
                    else {
                        sm.Status__c ='Registered' ;
                    }  
                }
                
                if(!sessioMCounter.containsKey(sm.session__c)){
                    sessioMCounter.put(sm.session__c,0);
                }
                sessioMCounter.put(sm.session__c,sessioMCounter.get(sm.session__c)+1);
                /*
                System.debug('----participant capacity----'+sessionMap.get(sm.session__c).Participant_Capacity__c);
                System.debug('----Session member size----'+sessionMap.get(sm.session__c).Session_Attendees__r.size());
                System.debug('----Session m Counter ----'+sessioMCounter.get(sm.session__c));
                System.debug('----test runing----'+test.isRunningTest());
                System.debug('----sm.status__c----'+sm.status__c);
                System.debug('----condition 1----sessionMap.get(sm.session__c).Session_Attendees__r.size()+sessioMCounter.get(sm.session__c)) > sessionMap.get(sm.session__c).Participant_Capacity__c---'+((sessionMap.get(sm.session__c).Session_Attendees__r.size()+sessioMCounter.get(sm.session__c)) > (sessionMap.get(sm.session__c).Participant_Capacity__c)));
                System.debug('----condition 2----sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size()---'+(sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size()));
                */
                System.debug('==sessionMap.get(sm.session__c).Participant_Capacity__c==='+sessionMap.get(sm.session__c).Participant_Capacity__c);
                if(mapSessionMembers.containsKey(sm.session__c)){
                    system.debug('======mapSessionMembers.get(sm.session__c)========'+mapSessionMembers.get(sm.session__c));
                }
                system.debug('======sessioMCounter.get(sm.session__c)========'+sessioMCounter.get(sm.session__c));
                
                
                if(test.isRunningTest() || (mapSessionMembers.containsKey(sm.session__c) && sessionMap.get(sm.session__c).Participant_Capacity__c!=null && (mapSessionMembers.get(sm.session__c)+sessioMCounter.get(sm.session__c)) > sessionMap.get(sm.session__c).Participant_Capacity__c) 
                //|| 
                //(sessionMap.get(sm.session__c).Participant_Capacity__c!=null && 
                //sessionMap.get(sm.session__c).Participant_Capacity__c < sessionMap.get(sm.session__c).Session_Attendees__r.size() )
                ){
                    
                    if(sm.Status__c != 'Registered-DB')
                        sm.Status__c='Registered-WL';
                    
                }
                System.debug('---final status---'+sm.Status__c);
                /*if(sm.contact__c!=null){
                    if(!mapContactSessions.containsKey(sm.contact__c)){
                        mapContactSessions.put(sm.contact__c,new List<Session__c>());
                    }
                    mapContactSessions.get(sm.contact__c).add(sessionMap.get(sm.session__c));
                }*/
                
            }
        }

        System.debug('=====final trigger======'+(List<Session_Member__c>)trigger.new);
        }catch(Exception e){
            //System.assert(false,e.getLineNumber()+'==============='+e.getstacktraceString()+'======='+e);
        }
    }
     public static String getSeesionMemberStatus(String cid,Session__c sess,Map<Id,List<Session__c>> contSet){
        String retStr='Registered';
        /* checking about DB*/
        if(checkSessionTimeFrame(cid,sess,contSet)){
             retStr='Registered-DB'; 
        }
        return retStr;
    }
    public static boolean checkSessionTimeFrame(String cid,Session__c sess,Map<Id,List<Session__c>> mapContactSessions){
        boolean retvar=false;
        if(mapContactSessions.containsKey(cid)){
                for(Session__c existingSession: mapContactSessions.get(cid)){
                    if(sess.id!=existingSession.id && sess.Campaign__c == existingSession.Campaign__c){
                        if(inBWChecker(existingSession.start__c,existingSession.end__c,sess.start__c) || 
                        inBWChecker(existingSession.start__c,existingSession.end__c,sess.End__c) || 
                        inBWChecker(sess.start__c,sess.end__c,existingSession.start__c) || 
                        inBWChecker(sess.start__c,sess.end__c,existingSession.End__c)){
                            retvar=true;
                            break;
                        }
                    }    
                }
            
        }
        return retvar;
    }
    public static boolean inBWChecker(datetime dt1,datetime dt2,datetime check){
       if(check >= dt1 && check <= dt2){
            return true;
        }
        return false;
    }
}

And the test class:
@isTest
Public class SessionMemberTriggerHandlerTEST {
    
    static testMethod void myUnitTest() {
        //Create test Campaign
        Campaign campaign = new Campaign(Name = 'Test Campaign',Contact_Field__c = 'Palm Springs 2014');
        insert campaign;
        //Create test Contact
        Contact contact = new contact(LastName = 'Test Last',Contact_Type__c = 'Prospect');
        insert contact;
        
        Session_Track_Name__c sessionTrack = new Session_Track_Name__c(Name = 'Track', Campaign__c = campaign.Id);
        insert sessionTrack;
        
        Session__c session = new Session__c(Name = 'Current session',Start__c=date.today(),End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session;
        Session__c session2 = new Session__c(Name = 'Current session 2',Start__c=date.today()+5,End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session2;
       
        List<Session_Member__c> smlist =  new List<Session_Member__c>();
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
       
        list<Session__c> slist =new list<Session__c> ();
        slist.add(session2);
        map<id,list<session__c>> mapsess = new map<id,list<session__c>>();
        mapsess.put(contact.id, slist);
        
     
        SessionMemberTriggerHandler shandler = new SessionMemberTriggerHandler();
        shandler.bulkAfter();
        shandler.beforeInsert();
        shandler.beforeUpdate();
        shandler.beforeDelete();
        shandler.afterInsert();
        shandler.afterUpdate();
        shandler.afterDelete();
        shandler.afterUnDelete();
        shandler.andFinally();
        shandler.bulkbefore();
        
        SessionMemberTriggerHandler.getSeesionMemberStatus(contact.id, session, mapsess);
        SessionMemberTriggerHandler.inBWChecker(date.today(), date.today()+9,date.today()+7);
        
        test.startTest();
        insert smlist;
        list<Session_Member__c > sessionList= [select Id from Session_Member__c where Id = :smlist[0].Id];
        system.assertEquals(1,sessionList.size() );
        test.stopTest();
       
        //SessionMemberTriggerHandler.updateSessionMember();
        Delete smlist;
    }
    static testMethod void myUnitTest2() {
        //Create test Campaign
        Campaign campaign = new Campaign(Name = 'Test Campaign',Contact_Field__c = 'Palm Springs 2014');
        insert campaign;
        //Create test Contact
        Contact contact = new contact(LastName = 'Test Last',Contact_Type__c = 'Prospect');
        insert contact;
        
        Session_Track_Name__c sessionTrack = new Session_Track_Name__c(Name = 'Track', Campaign__c = campaign.Id);
        insert sessionTrack;
        
        Session__c session = new Session__c(Name = 'Current session',Start__c=date.today(),End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session;
        Session__c session2 = new Session__c(Name = 'Current session 2',Start__c=date.today()+5,End__c=date.today()+9, Campaign__c = campaign.Id, Session_Track__c = sessionTrack.Id);
        insert session2;
       
        List<Session_Member__c> smlist =  new List<Session_Member__c>();
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        smlist.add(new Session_Member__c(Contact__c = contact.Id, Session__c = session.Id,Status__c ='Registered-DB'));
        insert smlist;
        
        list<Session__c> slist =new list<Session__c> ();
        slist.add(session2);
        map<id,list<session__c>> mapsess = new map<id,list<session__c>>();
        mapsess.put(contact.id, slist);
        
     
        SessionMemberTriggerHandler shandler = new SessionMemberTriggerHandler();
        shandler.bulkAfter();
        shandler.beforeInsert();
        shandler.beforeUpdate();
        shandler.beforeDelete();
        shandler.afterInsert();
        shandler.afterUpdate();
        shandler.afterDelete();
        shandler.afterUnDelete();
        shandler.andFinally();
        shandler.bulkbefore();
        
        SessionMemberTriggerHandler.getSeesionMemberStatus(contact.id, session, mapsess);
        SessionMemberTriggerHandler.inBWChecker(date.today(), date.today()+9,date.today()+7);
        test.startTest();
        update smlist;
        list<Session_Member__c > sessionList= [select Id from Session_Member__c where Id = :smlist[0].Id];
        system.assertEquals(1,sessionList.size() );
        test.stopTest();
       
        //SessionMemberTriggerHandler.updateSessionMember();
        Delete smlist;
    }
}

​The apex test errors i'm getting are: 

System.AssertException: Assertion Failed: 25===============Class.SessionMemberTriggerHandler.updateSessionMember: line 25, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest: line 40, column 1=======System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.SessionMemberTriggerHandler.updateSessionMember: line 172, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest: line 40, column 1

System.AssertException: Assertion Failed: 25===============Class.SessionMemberTriggerHandler.updateSessionMember: line 25, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest2: line 91, column 1=======System.NullPointerException: Attempt to de-reference a null object 
Stack Trace: Class.SessionMemberTriggerHandler.updateSessionMember: line 172, column 1 Class.SessionMemberTriggerHandler.bulkBefore: line 4, column 1 Class.SessionMemberTriggerHandlerTEST.myUnitTest2: line 91, column 1

Does anyone have any ideas? Thanks!
 
Best Answer chosen by Alex D 10
NForceNForce
Add a null check before this line, 
if(mapContactSessions.get(sm.contact__c)!=null){
 mapContactSessions.get(sm.contact__c).add(sessionMap.get(sm.session__c));
}

All Answers

NForceNForce

Hi Alex,

Line: mapContactSessions.get(sm.contact__c).add(sessionMap.get(sm.session__c));
map returns null for the sm.contact__c. value doesn't exist in the map. 

Thanks,

Alex D 10Alex D 10
Thank you for your reply! 

Where do I need to add sm.contact__c so that the map doesn't return null?
NForceNForce
Add a null check before this line, 
if(mapContactSessions.get(sm.contact__c)!=null){
 mapContactSessions.get(sm.contact__c).add(sessionMap.get(sm.session__c));
}
This was selected as the best answer
Alex D 10Alex D 10
That worked. Thank you so much!