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
Steven Wellman 23Steven Wellman 23 

System.NullPointerException: Attempt to de-reference a null object - AutoReg Handler - getting test coverage

I'm trying to write a test class so I can get over the 75% coverage (no coverage was written/included for this class). I'm getting the null object error on line 9 - System.assertEquals('testuserlong@salesforce.com', u.userName); 

Any help would be appreciated! Thanks in advance.

Here's the Class:
global class AutocreatedRegHandler1516897783772 implements Auth.RegistrationHandler{
global boolean canCreateUser(Auth.UserData data) {
    //TODO: Check whether we want to allow creation of a user with this data
    //Set<String> s = new Set<String>{'usernamea', 'usernameb', 'usernamec'};
    //if(s.contains(data.username)) {
        //return true;
    //}
    return false;
}

global User createUser(Id portalId, Auth.UserData data){
    if(!canCreateUser(data)) {
        //Returning null or throwing an exception fails the SSO flow
        return null;
    }
    //The user is authorized, so create their Salesforce user
    User u = new User();
    Profile p = [SELECT Id FROM profile WHERE name='Standard User'];
    //TODO: Customize the username. Also check that the username doesn't already exist and
    //possibly ensure there are enough org licenses to create a user. Must be 80 characters
    //or less.
    u.username = data.username + '@myorg.com';
    u.email = data.email;
    u.lastName = data.lastName;
    u.firstName = data.firstName;
    String alias = data.username;
    //Alias must be 8 characters or less
    if(alias.length() > 8) {
        alias = alias.substring(0, 8);
    }
    u.alias = alias;
    u.languagelocalekey = UserInfo.getLocale();
    u.localesidkey = UserInfo.getLocale();
    u.emailEncodingKey = 'UTF-8';
    u.timeZoneSidKey = 'America/Los_Angeles';
    u.profileId = p.Id;
    return u;
}

global void updateUser(Id userId, Id portalId, Auth.UserData data){
    User u = new User(id=userId);
    //TODO: Customize the username. Must be 80 characters or less.
    //u.username = data.username + '@myorg.com';
    u.email = data.email;
    u.lastName = data.lastName;
    u.firstName = data.firstName;
    //String alias = data.username;
    //Alias must be 8 characters or less
    //if(alias.length() > 8) {
        //alias = alias.substring(0, 8);
    //}
    //u.alias = alias;
    update(u);
}
}

Here's the Test Class:
@isTest
private class AutocreatedRegHandler1516897783772Test {
static testMethod void testCreateAndUpdateUser() {
    AutocreatedRegHandler1516897783772 handler = new AutocreatedRegHandler1516897783772();
    Auth.UserData sampleData = new Auth.UserData('testId', 'testFirst', 'testLast',
        'testFirst testLast', 'testuser@example.org', null, 'testuserlong', 'en_US', 'facebook',
        null, new Map<String, String>{'language' => 'en_US'});
    User u = handler.createUser(null, sampleData);
    System.assertEquals('testuserlong@salesforce.com', u.userName);
    System.assertEquals('testuser@example.org', u.email);
    System.assertEquals('testLast', u.lastName);
    System.assertEquals('testFirst', u.firstName);
    System.assertEquals('testuser', u.alias);
    insert(u);
    String uid = u.id;
     
    sampleData = new Auth.UserData('testNewId', 'testNewFirst', 'testNewLast',
        'testNewFirst testNewLast', 'testnewuser@example.org', null, 'testnewuserlong', 'en_US', 'facebook',
        null, new Map<String, String>{});
    handler.updateUser(uid, null, sampleData);
     
    User updatedUser = [SELECT userName, email, firstName, lastName, alias FROM user WHERE id=:uid];
    System.assertEquals('testnewuserlong@salesforce.com', updatedUser.userName);
    System.assertEquals('testnewuser@example.org', updatedUser.email);
    System.assertEquals('testNewLast', updatedUser.lastName);
    System.assertEquals('testNewFirst', updatedUser.firstName);
    System.assertEquals('testnewu', updatedUser.alias);
}
}
Raj VakatiRaj Vakati
please refer this link. 

You can get the test class how to write for the auth handler

https://github.com/salesforceidentity/social-signon-reghandler
Raj VakatiRaj Vakati
@isTest
private class AutocreatedRegHandler1516897783772Test {
testmethod public static void testCanCreateUser() {
	AutocreatedRegHandler1516897783772  handler = new AutocreatedRegHandler1516897783772 ();
	Auth.UserData data = createUser('test@example.com','John','Adams');
	
	System.Assert(handler.canCreateUser(data),'Handler should be able to create this user');
}

/**
 * Negative test for canCreateUser because insufficient detail is available
 **/     
testmethod public static void testCanCreateUserNegative() {
	AutocreatedRegHandler1516897783772  handler = new AutocreatedRegHandler1516897783772 ();
	Auth.UserData data = createUser(null,'Thomas','Jones-Drew');
	
	System.Assert(!handler.canCreateUser(data),'Handler should not be able to create user with missing email');
}

/**
 * Scenario where we want to provision an Internal User from Facebook
 **/ 
testmethod public static void testCreateInternalUser() {
	AutocreatedRegHandler1516897783772  handler = new AutocreatedRegHandler1516897783772 ();
	
	Auth.UserData data = createUser('tjones@example.com','Thomas','Jones-Drew');
	
	
	Test.startTest();
	
	User theUser = handler.createUser(null, data);
	
	Test.stopTest();
	
	validate(theUser,data);
	
}

/**
 * Scenario where we don't have enough detail to create a User end-to-end
 **/ 
testmethod public static void testCreateInternalUserNegative() {
	AutocreatedRegHandler1516897783772   handler = new AutocreatedRegHandler1516897783772 ();
	
	Auth.UserData data = createUser(null,'Thomas','Jones-Drew');
			
	Test.startTest();
	
	User theUser = handler.createUser(null, data);
	
	Test.stopTest();
	
	System.Assert(theUser==null,'User should be null for negative case');
	
}

/**
 * Simple direct test of the UpdateUser method.  Create the user first 
 * and then attempt to update some properties.
 **/ 
testMethod public static void testUpdateUser() {
	AutocreatedRegHandler1516897783772  handler = new AutocreatedRegHandler1516897783772 ();
	
	Auth.UserData data = createUser('tjones@example.com','Thomas','Jones-Drew');
	User theUser = handler.createUser(null, data);
	insert theUser;
	
	Test.startTest();
	
	validate(theUser,data);
	
	data.firstName='Tom';
	handler.updateUser(theUser.id, null, data);
	
	User theUpdatedUser = [SELECT Id,firstName,Email,LastName 
							 from User 
							Where Id = :theUser.id];
	
	validate(theUpdatedUser,data);
	
	Test.stopTest();

}


/**
 * Simple scenario to create a Community user
 **/ 
testmethod public static void testCreateCommunityUser() {
	AutocreatedRegHandler1516897783772  handler = new AutocreatedRegHandler1516897783772 ();
	
	Auth.UserData data = createUser('tjones@example.com','Thomas','Jones-Drew');
			
	Test.startTest();
	String theCommunityId = '00000001';
	data.attributeMap.put('sfdc_networkid',theCommunityId);
	
	User theUser = handler.createUser(null, data);
	
	Test.stopTest();
	
	validate(theUser,data);
	
	// Additional validations for Community User
	System.Assert(theUser.ContactId!=null,'Contact must be set for user');
	
}

/**
 * Helper method to Validate the the User we've created
 * 
 * @param theUser - the User that we created
 * @param data - the original AuthData supplied by FaceBook
 **/ 
private static void validate(User theUser, Auth.UserData data) {
	System.Assert(theUser!=null,'User must not be null');
	System.AssertEquals(theUser.email,data.email,'Email address must be the same');
	System.AssertEquals(theUser.FirstName,data.FirstName,'First name must match');
	System.AssertEquals(theUser.LastName,data.LastName,'Last name must match');
}


/**
 * Helper method to instantiate the handler UserData
 * 
 * @param email
 * @param lastName
 * @param firstName
 * @return Auth.UserData that looks like what we expect from FaceBook
 **/ 
private static Auth.UserData createUser(String email,String lastName, String firstName) {
	 Map<String, String> attributeMap = new Map<String,String>();
	 String identifier = lastName+System.currentTimeMillis();
	 String locale = 'en_US';
	 return new Auth.UserData( identifier,
		   firstName,
		   lastName,
		  '', // fullname
		   email,
		   '', // link
		   '', // userName
		   locale,
		   '', // provider
		   '', // siteLoginUrl
		   attributeMap);       
}
}

 
Steven Wellman 23Steven Wellman 23
@Raj, thanks for this! As I've run the test I've come up with the following errors:
  • testCanCreateUser
    • System.AssertException: Assertion Failed: Handler should be able to create this user
    • line 7
  • testCreateCommunityUser
    • System.AssertException: Assertion Failed: User must not be null
    • Class.AutocreatedRegHandler1516897783772Test.validate: line 116, column 1
    • Class.AutocreatedRegHandler1516897783772Test.testCreateCommunityUser: line 102, column 1
  • testCreateInternalUser
    • System.AssertException: Assertion Failed: User must not be null
    • Class.AutocreatedRegHandler1516897783772Test.validate: line 116, column 1
    • Class.AutocreatedRegHandler1516897783772Test.testCreateInternalUser: line 35, column 1
  • testUpdateUser
    • System.NullPointerException: Attempt to de-reference a null object
    • Class.AutocreatedRegHandler1516897783772Test.testUpdateUser: line 66, column 1
Thanks so much for your help! I truly appreciate it!