I am writing a trigger test class for a trigger that inserts a new task when the current task is saved. In the trigger I only want it to fire when the current user has a certain profile. Because of this, I am unable to get past that validation in testing since I am logged in as system administrator. is there a way to bypass this in the trigger test code?


There is this example in the Using the runAs Method documentation that shows how to switch profile in a test:

private class TestRunAs {

    static void testTriggerUsingRunAs() {

        // Create a unique UserName
        String uniqueUserName = 'user' + DateTime.now().getTime() + '@org.com';

        // Pick the Profile you want to test under here
        String profileName = 'Standard User';
        Profile p = [SELECT Id FROM Profile WHERE Name = :profileName];

        // Create a User object that uses that Profile
        User u = new User(
            UserName = uniqueUserName,
            ProfileId = p.Id,
            Alias = 'standt',
            Email = 'user@org.com',
            EmailEncodingKey = 'UTF-8',
            LastName = 'Testing',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',
            TimeZoneSidKey = 'America/Los_Angeles'

        System.runAs(u) {
            // Add your trigger test code here
            System.debug('Current User: ' + UserInfo.getUserName());
            System.debug('Current Profile: ' + UserInfo.getProfileId());

(I've changed this a bit for the context of your question.)

  • Amazing, thank you.
    – Carly
    Jul 16 at 12:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.