0

Below is my Test Class and I am getting the error : System.NullPointerException: Attempt to de-reference a null object error on line 23 .

@isTest
public class ShowRoom_VisitController_Test {
    //test class for ShowRoom_VisitController

    @isTest 
    Static Void TestOne(){

        Account Acc = new Account(Name = 'Test FM Account', Account_Type__c = 'B2C');
        insert Acc;

        Contact Con = new Contact(AccountId = Acc.Id, LastName = 'PortalContact');
        insert Con;

        Profile PortalProfile = [SELECT Id FROM Profile WHERE Name='HW - Showroom Community']; 
        User ShowroomUser = new User(Alias = 'sales', Email='portaluser@testorg.com', ContactId = Con.Id,
                                     EmailEncodingKey='UTF-8', LastName='Sales', LanguageLocaleKey='en_US', 
                                     LocaleSidKey='en_US', ProfileId = PortalProfile.Id, 
                                     TimeZoneSidKey = 'Asia/Dubai', UserName='ShowroomUser@cctestorg.com');
        insert ShowroomUser;

        Sales_Team__c ShowroomST = new Sales_Team__c(Account__c = Acc.Id, User__c = ShowroomUser.Id, Manager_User__c = UserInfo.getUserId());
        insert ShowroomST;
        Id targetRecordType = Schema.SObjectType.Invoice__c.getRecordTypeInfosByName().get('Target').getRecordTypeId();// This is my error line

        Invoice__c target = new Invoice__c(RecordTypeId = targetRecordType, Target_Start_Date__c = System.today(), Target_End_Date__c = System.today(),
                                           Sales_Team__c = ShowroomST.Id, Account__c = Acc.Id);
        insert target;

        Visit__c visit = new Visit__c();
        visit.Assigned_To__c = ShowroomUser.id;
        visit.Related_To__c = acc.Id;
        visit.Start__c = Date.today();
        visit.End__c = Date.today();
        insert visit;

        System.runAs(ShowroomUser){
            System.debug('user id: '+ShowroomUser.id);
            ShowRoom_VisitController vc = new ShowRoom_VisitController();
            vc.merchandiserAccounts = new List<Invoice__c>();
            vc.merchandiserAccounts.add(target);
            vc.LeftImageURL = '';
            vc.CheckIn();
            vc.coordinates = '30.1-31.2';
            vc.SelectedVisitId = Acc.Name;
            vc.ViewVisitsSchedule();
            vc.Visits.put(Acc.Name,visit);
            vc.CheckIn();
            vc.Visits.put(Acc.Name,visit);
            vc.CheckIn();

ShowRoom_VisitController.VisitsWrapper vw = new  ShowRoom_VisitController.VisitsWrapper (target.Account__r.Name,'String visitDate','String VisitId', 'String StartTime', 'String EndTime', 'String Store', 'String Status', 'tring mapUR',555.55,555.55, 'string DateCheckOut','string DateCheckIn','tring DateOfNow');
        }
    }

}

This is my apex class

public class ShowRoom_VisitController {
    /*this controller is for Showroom Profile only
it will only have check in and check out functionalities
*/

    public String LeftImageURL{get;set;}
    public String SelectedVisitId {get;set;}
    public List<VisitsWrapper> VisitsWrapperList{get;set;}
    public String coordinates{get;set;}
    public List<Sales_Team__c> teams {get;set;}

    public list<Invoice__c> merchandiserAccounts{get;set;}
    public map<String, Visit__c> Visits {get;set;} 
    public String userProfile {get;set;} 

    public ShowRoom_VisitController(){
        List< document > documentList=[select name from document where Name = 'Logo' Limit 1];
        if(documentList.size() > 0) LeftImageURL='/servlet/servlet.FileDownload?file=' + documentList[0].id;

        userProfile = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId() LIMIT 1].Name;

        if(userProfile == 'HW - Showroom Community'){
          merchandiserAccounts = [SELECT Id, Account__c, Account__r.Name FROM Invoice__c WHERE RecordType.DeveloperName = 'Target'
                                AND Sales_Team__r.User__c =: UserInfo.getUserId() 
                                AND Target_Start_Date__c <=: System.today() AND Target_End_Date__c >=: System.today()];
        } else{
            //merchandiserAccounts = [SELECT Id, Account__c, Account__r.Name FROM Invoice__c WHERE RecordType.DeveloperName = 'Target'
            //                    AND Sales_Team__r.Manager_User__c =: UserInfo.getUserId() ];
                                //AND Target_Start_Date__c <=: System.today() AND Target_End_Date__c >=: System.today()];
            teams = [select id, Account__c, Category__c, Brand__c,Account__r.Name from Sales_Team__c  where Manager_User__c  = :UserInfo.getUserId()];
        }


        Visits = new map<String, Visit__c>();
        VisitsWrapperList = new List<VisitsWrapper>();

        ViewVisitsSchedule();
    }



    public void ViewVisitsSchedule(){
        Set<Id> todayAccounts = new Set<Id>();
        if(userProfile == 'HW - Showroom Community'){
            for(Invoice__c t : merchandiserAccounts){
                todayAccounts.add(t.Account__c);
            }
        }else{
           for(Sales_Team__c t : teams){
                todayAccounts.add(t.Account__c);
            } 
        }
        Visits = new map<String, Visit__c>();
        for(Visit__c visit : [Select Start__c, End__c, Related_To__c, Related_To__r.name, Related_To__r.Store_Location_Latitude__c , Related_To__r.Store_Location_Longitude__c, Status__c,Latitude__c,Longitude__c ,latitudeOut__c,DateCheckOut__c,DateCheckIn__c,Related_Event_Id__c
                              From Visit__c Where Related_To__c IN :todayAccounts AND DAY_ONLY(Start__c) =: Date.today() AND Assigned_To__c =: UserInfo.getUserId() order by Start__c]){
                                  Visits.put(visit.Related_To__r.Name, visit);                      
                              }
        if(userProfile == 'HW - Showroom Community'){
            if(Visits.size() < merchandiserAccounts.size()){
                //some visits aren't created yet so, we create empty visits for them without committing them to the DB
                for(Invoice__c t : merchandiserAccounts){
                    if(! Visits.containsKey(t.Account__r.Name)){
                        //create an empty visit without saving it
                        Visits.put(t.Account__r.Name, new Visit__C(Status__c = 'Pending',Related_To__c = t.Account__c, Assigned_To__c = UserInfo.getUserId(),
                                                                   Start__c = System.now(), End__c = System.now()));
                    }
                }
            }
        }else{
           if(Visits.size() < teams.size()){
                //some visits aren't created yet so, we create empty visits for them without committing them to the DB
                for(Sales_Team__c t : teams){
                    if(! Visits.containsKey(t.Account__r.Name)){
                        //create an empty visit without saving it
                        Visits.put(t.Account__r.Name, new Visit__C(Status__c = 'Pending',Related_To__c = t.Account__c, Assigned_To__c = UserInfo.getUserId(),
                                                                   Start__c = System.now(), End__c = System.now()));
                    }
                }
            } 
        }
        VisitsWrapperList = new List<VisitsWrapper>();
        for(String s: Visits.keySet()){
            Visit__c v = Visits.get(s);
            datetime StartDateTime = v.Start__c;
            string StartTime = StartDateTime.format();
            datetime EndDateTime = v.End__c;
            string EndtTime = EndDateTime.format();
            string strCheckOutTime = '';
            if(v.DateCheckOut__c != null){
                datetime TimeCheckOut = v.DateCheckOut__c;
                strCheckOutTime = TimeCheckOut.format();
                strCheckOutTime = strCheckOutTime.substring(strCheckOutTime.length() - 8);
            }
            string strCheckInTime = '';
            if(v.DateCheckIn__c != null){
                datetime TimeCheckIn = v.DateCheckIn__c;            
                strCheckInTime = TimeCheckIn.format();
                strCheckInTime = strCheckInTime.substring(strCheckInTime.length() - 8);
            }
            if(v.Id != null) v.Status__c = 'Completed';
            VisitsWrapperList.add(new VisitsWrapper(s, StartDateTime.formatGMT('EEE, MMM d yyyy'),v.Id, StartTime.substring(StartTime.length() - 8), EndtTime.substring(EndtTime.length() - 8), v.Related_To__r.name, v.Status__c, v.Related_To__r.Store_Location_Latitude__c!=null?v.Related_To__r.Store_Location_Latitude__c:'' +''+ v.Related_To__r.Store_Location_Longitude__c!=null?v.Related_To__r.Store_Location_Longitude__c:'',v.Latitude__c,v.LatitudeOut__c,strCheckOutTime,strCheckInTime,system.now().formatGMT('EEE, MMM d yyyy')));
        }
    }

    Public PageReference CheckIn(){
        if(coordinates == null){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Unable to retrieve your location, please make sure that location service is open.');
            ApexPages.addmessage(myMsg);
            return null;
        }
        String[] LongAndLat = coordinates.split('-');
        System.debug('Visits Map: '+Visits);
        if(Visits.get(SelectedVisitId).Latitude__c == null || Visits.get(SelectedVisitId).Longitude__c == null){
            //check in part
            Visits.get(SelectedVisitId).Latitude__c = decimal.valueOf(LongAndLat[0]);
            Visits.get(SelectedVisitId).Longitude__c = decimal.valueOf(LongAndLat[1]);
            Visits.get(SelectedVisitId).DateCheckIn__c = system.now();
            upsert Visits.get(SelectedVisitId);
        }else{
            //check out part
            Visits.get(SelectedVisitId).LatitudeOut__c = decimal.valueOf(LongAndLat[0]);
            Visits.get(SelectedVisitId).LongitudeOut__c = decimal.valueOf(LongAndLat[1]);
            Visits.get(SelectedVisitId).DateCheckOut__c = system.now();
            upsert Visits.get(SelectedVisitId); 
        }
        //refill wrapper
        ViewVisitsSchedule();
        return null;
    }

    @TestVisible
    public class VisitsWrapper{
        public String VisitDate{get;set;}
        public String VisitId{get;set;}
        public String StartTime{get;set;}
        public String EndTime{get;set;}
        public String Store{get;set;}
        public String Status{get;set;}
        public String storeURL{get;set;}
        public String latitude{get;set;}
        public String latitudeOut{get;set;}
        public String DateCheckIn{get;set;}
        public String DateCheckOut{get;set;}
        Public String DateOfNow{get;set;} 
        public string StoreName{get;set;}

        public VisitsWrapper(string storeName, String visitDate,String VisitId, String StartTime, String EndTime, String Store, String Status, String mapURL,decimal latitude,decimal latitudeOut ,  string DateCheckOut,string DateCheckIn,string DateOfNow){
            this.VisitId = VisitId;
            this.StartTime = StartTime;
            this.StoreName = storeName;
            this.EndTime = EndTime;
            this.Store = Store;
            this.Status = Status;
            this.storeURL = mapURL;
            this.visitDate = visitDate;
            this.DateCheckIn=DateCheckIn;
            this.DateCheckOut =DateCheckOut;

            this.latitudeOut=string.valueOf(latitudeOut);
            this.latitude=string.valueOf(latitude);
            this.DateOfNow = DateOfNow;
        }
    }

}
1
  • your subject line and your question content display 2 different error messages. Which one is the correct one? – Guy Clairbois Apr 20 '20 at 10:20
0

You might be using the wrong method for fetching the recordtype id. Are you sure that 'Target' is the label of that recordtype? Anyway I'd recommend to use getRecordTypeInfosByDeveloperName instead of getRecordTypeInfosByName because the developerName is unlikely to change, while recordtype Label might change without people realizing that your code is dependant on it.

getRecordTypeInfosByDeveloperName()

Returns a map that matches developer names to their associated record type. The current user is not required to have access to a record type to see it in this map.

getRecordTypeInfosByName()

Returns a map that matches record labels to their associated record type. The current user is not required to have access to a record type to see it in this map.

1
  • Thank you so much @Guy Clairbois I changed the record type Name and It worked. Thanks a lot!! – Anonymous123 Apr 20 '20 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.