Monday 29 February 2016

How to avoid this error while running test class "FIELD_CUSTOM_VALIDATION_EXCEPTION, Attempt to de-reference a null object: []"

This post is all about how efficiently custom settings can be used in the class so that we can avoid null pointer exception while running test class with seealldata is false.

As per the best practice concern, we should not use SeeAlldata is true in all the test class.If we wont use that attribute then we need to create all the test data(custom setting record and object record ) in the test class. We might not aware of all the custom setting which will be required to be inserted because they will be refereed in the trigger of some other object which is not really required to be executed.

Normally we use custom setting like below 

 Boolean ischecked = customsettingname__c.getInstance('RecordName').IsChecked__c ;

If we wont insert record name as "RecordName" in the custom setting customsettingname__c in test class , then we will come across this issue   FIELD_CUSTOM_VALIDATION_EXCEPTION, Attempt to de-reference a null object: []"

To avoid such issue we need to use custom setting like below 

Map<String, customsettingname__c> mcs = customsettingname__c.getAll();
System.debug('Printing--'+mcs );

if(mcs.keyset().size()>0 && mcs.containskey('RecordName'))
{
Boolean ischecked = customsettingname__c.getInstance('RecordName').IsChecked__c;
System.debug('Printing--'+ischecked);
}

3 comments:

Unknown said...

Thank You ashish behra.

Unknown said...

Thank you Asish Behra.It is really usefull.

Unknown said...

Thank u Asish .