[SalesForce] Test Method throwing null pointer exception on custom setting

I am trying to write a test class.

My Apex class has the following constructor:

public NController(ApexPages.StandardController controller) {

    cas =  (Case) controller.getRecord();
    csId = cas.Id;
    owner = cas.OwnerId;

    N_SSettings__c nhdsms = N_SSettings__c.getValues('Int');
    rate=nhdsms.Rate_Code__c;
    accId=nhdsms.Acc_Id__c;

}

Here N_SSettings__c is a custom settings which has two fields Rate_Code__c and Acc_Id__c. It has a record called 'Int' with both Rate_Code__c and Acc_Id__c field values populated.

I am using the following test class method:

@isTest
public class NHSsendSMSController_Test
{
    public static testMethod void NHSsendSMSControllerTest()
    {
        Case caseObj = new Case();
        insert caseObj;
        ApexPages.StandardController sc = new ApexPages.standardController(caseObj);
        NController nControllerObj = new NController(sc);
        nControllerObj.methodName();
    }
}

When I run the test method, it is throwing a null pointer exception on the line :

rate = nhdsms.Rate_Code__c;

The custom setting is definitely present with the required values of both the fields of Int.

Best Answer

You have to create your own test data.

Isolation of Test Data from Organization Data in Unit Tests

Starting with Apex code saved using Salesforce API version 24.0 and later, test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in your tests such as:

  • User
  • Profile
  • Organization
  • AsyncApexJob
  • CronTrigger
  • RecordType
  • ApexClass
  • ApexTrigger
  • ApexComponent
  • ApexPage

So if you want this call to return data:

N_SSettings__c.getValues('Int')

Then you have to set it up in your test:

insert new N_SSettings__c(Name='Int', OtherFields__c='Some Values');

Or you could use a Custom Metadata Type instead, which would be visible in the test context without using SeeAllData=true.

Related Topic