You need to sign in to do that
Don't have an account?
![savvyboarder savvyboarder](https://dfc-org-production.my.site.com/img/userprofile/default_profile_45_v2.png)
system.runAs & Test Methods
Hi all-
I'm curious if anybody knows what I might be doing wrong here...
I'm trying to run this test as a different user, and it's setting the correct user, but the "CreatedById" isn't being populated when inserting.
Is there something I'm missing in the code?
Cheers!!
// this tests trgCreateOpptyTask
// create a couple opptys and then update them with a unit_id
test.starttest();
Profile p = [SELECT Id FROM profile WHERE name='API'];
User u1 = new User(alias = 'newUser', email='user@mydomain.com',
emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id,
timezonesidkey='America/Los_Angeles', username='user@mydomain.com');
system.debug('###### the user is: ' + u1.Email);
System.runAs(u1)
{
List<Opportunity> opportunities = new List<Opportunity>();
Opportunity o1 = new Opportunity();
o1.Name = 'Test Oppty 1';
o1.CloseDate = Date.today();
o1.StageName = 'Reservation';
o1.Rental_Rate__c = 100;
opportunities.add(o1);
Opportunity o2 = new Opportunity();
o2.Name = 'Test Oppty 2';
o2.CloseDate = Date.today();
o2.StageName = 'Appointment';
opportunities.add(o2);
Opportunity o3 = new Opportunity();
o3.Name = 'Test Oppty 3';
o3.CloseDate = Date.today();
o3.StageName = 'Lead';
opportunities.add(o3);
insert opportunities;
}
You never commit the user to the database. Add the following statement and it should work:
User u1 = new User(alias = 'newUser', email='user@mydomain.com',
emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id,
timezonesidkey='America/Los_Angeles', username='user@mydomain.com');
insert u1;
Thanks for the reply micwa! That makes sense since I wasn't getting the u1.Id back. Thanks for the tip. Unfortunately, after inserting the user record i'm getting an errror saying "System.Exception: Too mandy System.runAs() invocation: 1".
I'm only using it one time. Does anybody know why this would be happening?