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 LastNameAS Fixture, and AccountAS Setup Northowned by that user- any later test method → sees both rows without inserting them again
logCallAs(fixture)→ a TaskAS Callwhose CreatedById is the fixture user's Id
Requirements:
- 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. - Insert the User inside
System.runAs(new User(Id = UserInfo.getUserId())), with a unique Username. - Insert Account
AS Setup NorthwithOwnerIdset to the fixture user. - In
logCallAs, insert the Task insideSystem.runAs(fixture)and return its Id. - Keep
seedandlogCallAspublic static. The checks callseed()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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.