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

  • How to insert a user in test class in salesforce?

    Posted by Prachi on October 4, 2019 at 11:26 AM

    How to insert a user in test class in salesforce?

    • This discussion was modified 7 years ago by  Prachi.
    Yogesh replied 7 years ago 2 Members · 1 Reply
  • 1 Reply
  • 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 = ‘test@test.com’;
    user.email = ‘test@test.com’;
    insert user;
    system.runAs(user){
    Campaign campaign = new Campaign();
    campaign.name = ‘laptop’;
    insert campaign();
    }
    }
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos