Skip to content

Instantly share code, notes, and snippets.

@douglascayers
Last active June 18, 2016 05:00
Show Gist options
  • Save douglascayers/5ec24d559d630948892fa91d6f57d1f1 to your computer and use it in GitHub Desktop.
Save douglascayers/5ec24d559d630948892fa91d6f57d1f1 to your computer and use it in GitHub Desktop.
Apex Test function for creating new users.
@isTest
private class MyTestClass {
@isTest
static void test_something() {
Profile p = [ SELECT id FROM Profile WHERE name = 'Standard User' ];
User user1, user2;
// https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm
System.runAs( new User( id = UserInfo.getUserId() ) ) {
user1 = newUser( p.id, 'Alpha', 'User 1', '[email protected]' );
user2 = newUser( p.id, 'Beta', 'User 2', '[email protected]' );
insert new List<User>{ user1, user2 };
}
// TODO
}
private static User newUser( ID profileId, String firstName, String lastName, String email ) {
Integer rand = Math.round( Math.random() * 1000 );
return new User(
isActive = true,
profileId = profileId,
alias = firstName.substring(0,1) + lastName.substring(1,5),
firstName = firstName,
lastName = lastName,
email = email,
username = rand + email,
emailEncodingKey = 'UTF-8',
languageLocaleKey = 'en_US',
localeSidKey = 'en_US',
timeZoneSidKey = 'America/Chicago'
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment