I have a custom setting(list) with a custom field, which is accessed in the apex class in the sandbox. When I deploy the custom setting, custom field, apex class and test class to the Production, the validation fails with the error message : Attempt to de-reference a null object. And this error points the line number where there is a getInstance method to access the data in the custom setting. So do I have deploy the custom setting and custom field first, create the data and then deploy the apex class and test class. Is there any better way of handling this? Thanks.
1 Answer
If you are using an API Version
above 23.0
, your test will default to SeeAllData=false
. Therefore you need to create your own data. Note that Custom Settings
need to be inserted by a System Administrator
.
@IsTest
class MyTestClass
{
static final String INSTANCE_NAME = 'testData';
static final String CUSTOM_URL = 'www.sampleurl.com';
static User ADMIN_USER
{ // this should be in a public test utility somewhere
get
{
if (ADMIN_USER == null)
{
ADMIN_USER = [
SELECT Id FROM User
WHERE IsActive = true
AND Profile.Name = 'System Administrator'
LIMIT 1
];
}
return ADMIN_USER;
}
set;
}
static void setupCustomSetting()
{
My_Custom_Setting__c customSetting = new My_Custom_Setting__c();
customSetting.MyCustomField__c = 'www.sampleurl.com';
system.runAs(ADMIN_USER)
{
insert customSetting;
}
}
static testMethod void testMyMethod()
{
setupCustomSetting();
Test.startTest();
My_Custom_Setting__c instance = My_Custom_Setting__c.getInstance(INSTANCE_NAME);
Test.stopTest();
system.assertNotEquals(null, instance);
system.assertEquals(CUSTOM_URL, instance.MyCustomField__c);
}
}
-
Thanks for your answer. Let's say, My_Custom_Setting__c has a custom field mycustomfield__c. There is one data with Name as 'testdata' and mycustomfield__c as an 'www.sampleurl.com' url. In the apex class, we get the instance --> String strCustomUrl = My_Custom_Setting__c.getInstance('testdata').mycustomfield__c; So in the test class you've given, we are inserting the custom setting. How to insert the field and data.– SeeshFeb 2, 2015 at 22:08
-
SeeAllData
and counting on the Custom Settings existing already. If you really can't fix the test, you could deploy just the Custom Setting first, populate it, then deploy the class and test.