Activity Forums Salesforce® Discussions How to insert a user in test class in salesforce?

  • Yogesh

    Member
    October 4, 2019 at 1:50 pm

    Hello,

    Here is the example to use System.runAs() in apex test class: For example we have a class to create the campaign only if logged in user is marketing profile otherwise throwing error.

    Example:-

    // Apex Trigger

    trigger campaignBeforeInser on Account (before insert) {
    for(Campaign campaign: trigger.new){
    if(userInfo.getProfileId == ‘marketing profile Id’){
    campaign.currency = ‘USD’;
    }
    else{
    campaign.addError(‘you are not authorized to create campaign’);
    }
    }
    }
    //Here is the Test class for above trigger.

    @isTest
    private class CampaignTriggersTest{
    private static testmethod void campaignTriggersTest(){
    Profile prof = [select id from profile where name LIKE '%marketing%'];
    User user = new User();
    user.firstName = ‘test1’;
    user.lastName = test2;
    user.profileId = prof.id,username = ‘[email protected]’;
    user.email = ‘[email protected]’;
    insert user;
    system.runAs(user){
    Campaign campaign = new Campaign();
    campaign.name = ‘laptop’;
    insert campaign();
    }
    }
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos