ApexSensei

Drills › Prove it with tests

Share setup and run as another user

Prove it with tests · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A sharing test needs one fixture user and Account that every test method can see, and it must act as that user.

Create a fixture user and Account in @TestSetup, then use System.runAs to insert a Task as that user.

What you will learn

@TestSetup runs once per class, and every test method sees its rows. A fixture is a record a test needs — here, a known User and Account. System.runAs(user) runs a block as that user, so records inserted inside it are created by that user.

System.runAs(fixture) {
    insert new Task(Subject = 'AS Call');
}

Gotcha. Setup objects (a User with a role) and regular records can't share one transaction — that's a mixed DML error. System.runAs gives them separate contexts.

The task

Finish seed() so it creates a fixture user and an Account that user owns, and make logCallAs insert a Task as that user.

Examples:

  • seed() → a User with LastName AS Fixture, and Account AS Setup North owned by that user
  • any later test method → sees both rows without inserting them again
  • logCallAs(fixture) → a Task AS Call whose CreatedById is the fixture user's Id

Requirements:

  1. Find the Profile by what it can do, not by its name, which can differ between orgs: UserType = 'Standard', UserLicense.LicenseDefinitionKey = 'SFDC', PermissionsModifyAllData = false, PermissionsEditTask = true.
  2. Insert the User inside System.runAs(new User(Id = UserInfo.getUserId())), with a unique Username.
  3. Insert Account AS Setup North with OwnerId set to the fixture user.
  4. In logCallAs, insert the Task inside System.runAs(fixture) and return its Id.
  5. Keep seed and logCallAs public static. The checks call seed() from their own @TestSetup.

Starter code

@IsTest
public class AS_CB16E9892B08_SharingTests {
    @TestSetup
    static void setup() {
        seed();
    }

    public static void seed() {
        insert new Account(Name = 'AS Setup North');
    }

    public static Id logCallAs(User fixture) {
        Task call = new Task(Subject = 'AS Call');
        insert call;
        return call.Id;
    }
}

When it passes

Setup rows are visible in every test method. The Account is owned by the fixture user, and a Task inserted in System.runAs(fixture) is created by that user.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Mock an HTTP callout