[SalesForce] how to write test class for running user

Below is my test class in salesforce apex:-

@isTest
public class Testopoffers{
    @isTest
    private static void testRun(){
        Contact c = new Contact(AccountId = '001g000000OPOr1',LastName = 'test');
        insert c;
        Profile p = [SELECT Id FROM Profile WHERE Name='OnlineForms User']; 
        User u = new User(Alias = 'standt', Email='onlineforms@testorg.com', 
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',ContactId = c.id, 
        LocaleSidKey='en_US', ProfileId = p.Id, 
        TimeZoneSidKey='America/Los_Angeles', UserName='onlineforms@testorg.com');
        System.runAs(u){
        System.debug('Current User: ' + UserInfo.getUserName());
        System.debug('Current User ID: ' + UserInfo.getUserId());
            dsmtOpOffersCntlr dopc = new dsmtOpOffersCntlr();
            String pageRef = dopc.updateDSMTracker().getUrl();
            System.assertEquals('/default/dsmtManageEnrollmentApplicationUser', pageRef);
        }
    }

}

And below is the class and function for which the above test class is for :-

global class dsmtOpOffersCntlr{

    public pagereference updateDSMTracker(){
       u.DSMTracker_Show_Help_Splash_Screen__c=true;
       update u;
       return null;
    }

    public dsmtOpOffersCntlr(){

        u =[Select DSMTracker_Show_Help_Splash_Screen__c  from User where id=:UserInfo.getUserId()];       

    }
}

The above test class is giving the following error in debug logs :-
System.NullPointerException: Attempt to de-reference a null object

User is creating correctly for your information.
Please can anybody give me correct syntax to write the test class for above class and method ? Thanks in advance.

Best Answer

The method below returns null in your code

public pagereference updateDSMTracker(){
   u.DSMTracker_Show_Help_Splash_Screen__c=true;
   update u;
   return null;
}

When the line below executes you are getting a NullPointerException because you are trying to call getUrl() on null

String pageRef = dopc.updateDSMTracker().getUrl();
Related Topic