How to use system.runAs()|Apex test class Example

How to use system.runAs()?

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.




// 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();
}
}
}




Leave a Reply