Thursday, 19 November 2015

Simple solutions first - Test Class on User object

Test Class

Do you really need to create that new user in your Apex Test class?

This is just a short blog post on an "ah ha" moment I had the other day whilst coding.

After I had nearly finished creating lines of code to create a few user records in the Test Class I realised that I could have just used a $User global variable instead.

Why create user records in Test Classes?

I was creating a Trigger that would automatically populate an Opportunity if certain criteria were met in a new Account insertion.

In the production environment the Opportunity owner is the same as the Account Owner. To simulate the assignment of ownership in the Test Class for the trigger I needed to insert a valid user ID.

Approach 1 - Create a new user in Test Class

In the first instance I used this code snippet below to create a User record in the test class. More information on this can be found on the Salesforce Developer's Guide post.

private class TestRunAs {
    public static testMethod void testRunAs() {
        // Setup test data
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        User u = new User(Alias = 'standt', Email='', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='');


There is also more information on this StackExchange question which I found really useful.

Approach 2 - Use the Global Variable UserInfo.getUserId()

In my particular example I only needed to populate a valid User ID into the Opportunity record. All I needed to do for that was,
Opportunity opp =new Opportunity();
opp.Owner= UserInfo.getUserId();


Creating a user in a Test Class gives you a lot of flexibility. You can even several different users with different roles/permissions and then use the RunAs() function to test against different user scenarios. However, if if you just need an idea the UserInfo approach can save time.