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
Pooja Singh 21Pooja Singh 21 

System.NullPointerException: Attempt to de-reference a null object

Hi All,

My test class compiles succussfully. However, I receive an error while running it. I have no idea where I have done wrong. Please help.

Class.LC_DisplayFolderElementsController.displayFolderElements: line 99, column 1
Class.LC_DisplayFolderElementsController.<init>: line 77, column 1
Class.Test_LC_DisplayFolderElementsController.myUnitTest: line 49, column 1

Apex Class Code:
public with sharing class LC_DisplayFolderElementsController {
  
  public Consumer_Inquiries__c CI;
  public Access_Token__c gats;
  public captureFileElements cfe;
  
  public list<displayAttachments> Box_Attachments{get;set;}
  public list<FileEntries> Files;
  
  public boolean displayIFrame{get;set;}
  public displayAttachments dat;
  
  
  public LC_DisplayFolderElementsController(apexpages.standardController sc){
    gats = new Access_Token__c();
    CI = new Consumer_Inquiries__c();
    cfe = new captureFileElements();
    displayIFrame = false;
    dat = new displayAttachments();
        
    Id CIID = apexpages.currentPage().getParameters().get('ID');
    CI = [Select Id, Name, RecordTypeID, Folder_ID__c, (select Id, Name, ContentType from Attachments) from Consumer_Inquiries__c Where Id =: CIID];
    
    list<RecordType> RTList = new list<RecordType>();
    RTList = [Select Id, Name from RecordType Where sObjectType = 'Consumer_Inquiries__c' and Name = 'Regulatory Complaint'];
    RecordType RCRT;
    if(RTList != Null && RTList.size() > 0){
      for(RecordType rt : RTList){
        RCRT = rt;
      }
    }
    
    gats = [Select Id, Name, Token__c, Refresh_Token__c, LastmodifiedDate From Access_Token__c];
    Box_Attachments = new list<displayAttachments>();
    Files = new list<FileEntries>();
    if(CI != Null){//Adding the Existing Attachments into list for the Specific CI 
      for(Attachment att : CI.attachments){
        dat = new displayAttachments();
        dat.Attachment_Name = att.name;
        dat.FileID = '';
        dat.location = 'Salesforce';
        string Extension;
        if(att.name != Null && att.name != ''){
          integer IndexValue= att.name.lastIndexOf('.');
          if(IndexValue > -1){
            Extension = att.name.substring(IndexValue+1,att.name.length());// to show the actual file extension from salesforce
          } 
        }
        dat.Type = Extension;
        Box_Attachments.add(dat);
      }
    }
    
    if(Box_Attachments != Null && Box_Attachments.size() > 0){
      displayIFrame = true;
    }else{
      displayIFrame = false;
    }
    
    list<Firm_s_Child__c> FolderMapList = new list<Firm_s_Child__c>();
    FolderMapList = [Select Id, Name, Box_Folder_ID__c from Firm_s_Child__c Where Reference_ID__c =: CIID and Type__c = 'Consumer Inquiry'];
    if(FolderMapList != Null && FolderMapList.size() > 0){
      displayFolderElements(FolderMapList[0].Box_Folder_ID__c);
    }else{
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please try after some time as the folder has not yet created.'));
    }  
  }

  public void displayFolderElements(string FolderID){//Folder Id is picked up from Box Folder ID Map Table
    HTTPResponse res = new HTTPResponse();
    HTTPRequest req = new HTTPRequest();
    gats = [Select Id, Name, Token__c, Refresh_Token__c, LastmodifiedDate From Access_Token__c];
    req.setEndpoint('https://api.box.com/2.0/folders/'+FolderID+'/items');//Request URL for Folder Elements
    req.setHeader('Authorization','Bearer '+gats.Token__c);
    req.setMethod('GET');
    HTTP getFolderItems = new HTTP();
    res = getFolderItems.send(req);//Sending the request to get the actual response
    string bodystring = res.getBody();
    system.debug('The JSON Body is'+res.getBody());
    if(res.getStatusCode() == 200){
      cfe = (captureFileElements)JSON.deserialize(bodyString,captureFileElements.class);// Parsing the above request
      Files = cfe.entries;
  
      
      for(FileEntries fe : Files)
      {////Adding the Box Files into list for the Specific CI
        string str;
        integer dotIndex;
        
        dat = new displayAttachments();
        dat.Attachment_Name = fe.name;
        dat.FileID = fe.id;
        dat.location = 'Box';
        
        if(fe.name.contains('.')){
          str = fe.name;
          dotIndex = fe.name.lastIndexOf('.');
          system.debug('The dot Index is'+dotIndex);
          system.debug('The Type could be '+str.substring(dotIndex+1,str.length()));
          string str2 = str.substring(dotIndex+1,str.length());
          dat.Type = str2;
        }
        Box_Attachments.add(dat);
        if(Box_Attachments != Null && Box_Attachments.size() > 0){
          displayIFrame = true;
        }else{
          displayIFrame = false;
        }
      }
    }else{
      ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.ERROR,'Please try after some time as the folder has not yet created.'));
    }
    system.debug('The box Attachments are'+Box_Attachments);
  }
  
  public class displayAttachments{
    public string Attachment_Name{get;set;}
    public string FileID{get;set;}
    public string Type{get;set;}
    public string location{get;set;}
    
    public displayAttachments(){
      Attachment_Name = '';
      FileID = '';
      Type = '';
      location = '';
    }
  }
  
  /* File Wrapper*/
  public class captureFileElements{
    public integer total_count;
    public list<FileEntries> entries;
    public integer offset;
    public integer limit2;
    public list<Orders> Order;
    
    public captureFileElements(){
    }
  }
  /* File Wrapper*/
  /* File Wrapper*/
  public class FileEntries{
    public string Type;
    public string id;
    public string sequence_id;
    public string etag;
    public string sha1;
    public string name;
  }
  /* File Wrapper*/
  /* File Wrapper*/
  public class orders{
    public string by1;
    public string direction;
  }
  /* File Wrapper*/
}


Test Class:
@isTest(seealldata=true)
private class Test_LC_DisplayFolderElementsController{
     static testMethod void myUnitTest(){
        List<Account> accList = new list<Account>();
        Account a = new Account();
        a.Name = 'TestAcc';
        a.Firm_ID__c = 'Test';
        insert a;
        accList.add(a);
        
        list<Attachment> AttachmentList = new list<Attachment>();
        list<Consumer_Inquiries__c> ciList = new list<Consumer_Inquiries__c>();
        list<Case> caseList = new list<Case>();
        
        caseList = LC_TestDataUtility.createCases(1);
        ciList = LC_TestDataUtility.createConsumerInquiries(accList);
        system.assertEquals(1, ciList.size());
        system.assertEquals(1, caseList.size());
        
        list<Firm_s_Child__c> fc1 = new list<Firm_s_Child__c>();
        List<Box_Folder_ID_Map__c> BoxFolderIDList = [select Actual_Firm__c, Reference_ID__c, Firm_ID__c, Type__c, Created_Date__c from Box_Folder_ID_Map__c where Actual_Firm__c =: a.id and Reference_ID__c =: a.id and Type__c = 'Account' limit 1];
        system.debug('box folder id list value-->'+BoxFolderIDList );
        Firm_Dates__c fd = new Firm_Dates__c();
        fd.Box_Folder_ID_Map__c = BoxFolderIDList[0].id;
        fd.Folder_ID__c = '098745434';
        insert fd;
        
        Firm_s_Child__c fc = new Firm_s_Child__c();
        fc.Case_Reference__c = caseList[0].id;
        fc.Consumer_Inquiries_Reference__c = ciList[0].id;
        fc.Firm_Date__c = fd.id;
        fc.Type__c = 'Consumer Inquiry';
        fc.Box_Folder_ID__c = '09875432587';
        insert fc;
                
        fc1.add(fc);
        system.debug('fc1 value-->'+fc1);
        set<Id> parentIds = new set<Id>();
        parentIds.add(ciList[0].Id);
        AttachmentList = LC_TestDataUtility.createAttachments(parentIds);
        system.debug('consumer inquiry value-->'+ciList);
        
        Test.startTest();
        LC_DisplayFolderElementsController.displayAttachments obj1 = new LC_DisplayFolderElementsController.displayAttachments();
        LC_DisplayFolderElementsController.captureFileElements obj2 = new LC_DisplayFolderElementsController.captureFileElements();
        LC_DisplayFolderElementsController.FileEntries obj3 = new LC_DisplayFolderElementsController.FileEntries();
        Apexpages.currentPage().getParameters().put('ID',ciList[0].Id);
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        if(!fc1.isEmpty()){ 
        Apexpages.standardController sc = new Apexpages.standardController(fc1[0]);
        
        LC_DisplayFolderElementsController obj = new LC_DisplayFolderElementsController(sc);
        obj.displayFolderElements(fc1[0].Box_Folder_ID__c);
        
        LC_DisplayFolderElementsController.orders obj4 = new LC_DisplayFolderElementsController.orders();
        LC_DisplayFolderElementsController.displayAttachments obj5 = new LC_DisplayFolderElementsController.displayAttachments();
        }
        Test.stopTest();
     }
}
Himanshu ParasharHimanshu Parashar
Hi Pooja,

It seems like that str variable is coming null that is why you are getting this error, Try to put that code at line 98 and check debug log.
 
system.debug('Str value is :***********'+str);

Thanks,
Himanshu
Pooja Singh 21Pooja Singh 21
Thanks for your reply Himanshu.

None of the debug statements gets printed inside the if(fe.name.contains('.')){ loop. I suppose, the if condition is not getting satisfied in the test code. Please suggest the next step.
Pooja Singh 21Pooja Singh 21
I checked that Files value is NULL in-->  for(FileEntries fe : Files) loop. However, it shouldn't be. Its getting complex.
Nishant SharmaNishant Sharma
Honestly, I don't know where the problem is until I debug. But I suspect below piece of code to be the problem:
 
res = getFolderItems.send(req);//Sending the request to get the actual response

You can not send http request in context of test execution. I am wondering, if you are encountering similar problem. If yes, do this:
string bodystring = '';

if(!Test.isRunningTest()) {

	res = getFolderItems.send(req);//Sending the request to get the actual response
    bodystring = res.getBody();
}
else {
	
	//Store fake response in bodystring. In your case, it looks like json response. Below is just sample. Frame your response accordingly.
	bodystring = '{"total_count":0,"offset":1,"limit2":0}';
}
Pooja Singh 21Pooja Singh 21
I am afraid but the HTTP Request is not getting send in context of test execution. 
Nishant SharmaNishant Sharma
Yeah, so go for above solution. Whats the problem?