
Because this runAs method will create opportunities as different users and I have a trigger on Opportunity which executes a SOQL on the User object, the SOQL itself is executed as the user defined in the runAs method. Now for some unclear reason, I receive an error that there was no record to assign to a variable (see example)
User aUser = [ SELECT Id FROM User WHERE isActive = true AND Profile.Name = 'System Administrator' LIMIT 1 ];
Every user / profile associated with user which could possibly run this query has at least read access to the user object (sharing rules). I don't know if they have default access to the Profile object, but if that would be the problem, I'd expect another error message. The one I receive is the following:
System.QueryException: List has no rows for assignment to SObject
I'd expect an insufficient cross-object access error if Profile.Name would not be available...
Do you have insights on that?Hi Roger ,Please use like this it will not throw you MIX_DML_Operation Error . @isTest
private class TestRunAs {
public static testMethod void testRunAs() {
// Setup test data
// This code runs as the system user
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
LocaleSidKey='en_US', ProfileId = p.Id,
TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
System.runAs(u) {
// The following code runs as user 'u'
System.debug('Current User: ' + UserInfo.getUserName());
System.debug('Current Profile: ' + UserInfo.getProfileId());
}
}
}