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
Muhammad Hammad 8Muhammad Hammad 8 

how to write apex test for custom settings?

How to write apex test for void method with custom settings?I have a list custom setting.
 
public string name {get;set;}
    public string name2{get;set;}
    public String setting_1{get; set;}
    public String setting_2{get; set;}


public void set(){
        myuser__c setting = myuser__c.getInstance('mydata');
        name = setting.data__c;
        name2= setting.data2__c;
    }
    
    public void save(){
        myuser__c setting = myuser__c.getInstance('mydata');
        setting.data__c = setting_1;
        setting.data2__c = setting_1;
        update setting;
    }
    
    public void reset(){
    myuser__c setting = myuser__c.getInstance('mydata');
        setting.data__c = '';
        setting.data2__c = '';
        update setting;
    }
 
@isTest
private class SettingsTest{
    
    
    @testSetup static void setup() {

    myuser__c setting = new myuser__c();
        setting.Name = 'data__c';
        setting.data__c = 'test_name';
        //setting.Name = 'data2__c';
        //setting.data2__c = 'test_name2';
        insert setting;
    }

     static testmethod void testSetCustomSettings() {
       Settings myclass = new Settings();
       myclass.set();


    }
    
}

when I run the test it gives the error:  System.NullPointerException: Attempt to de-reference a null object
Best Answer chosen by Muhammad Hammad 8
Ashish Singh SFDCAshish Singh SFDC
Hi Muhammad Hammad 8,

Your method is expecting a record with Name "mydata". But you're creating a custom Setting with Name "data__c". 

Thanks,
Ashish Singh.

All Answers

Ashish Singh SFDCAshish Singh SFDC
Hi Muhammad Hammad 8,

Your method is expecting a record with Name "mydata". But you're creating a custom Setting with Name "data__c". 

Thanks,
Ashish Singh.
This was selected as the best answer
Muhammad Hammad 8Muhammad Hammad 8
Thanks alot Ashish.