Skip to main content
Dear Community

I have a couple of apex handler classes which are executed on certain trigger actions. It so comes that the test classes of the individual apex classes do interfere with one another.

So I might have some code executed on an OpportunityLineItem insertion which updates the Opportunity. For the test class i need to create an test opportunity record which will also cause all my triggers on opportunity to run.

All of this is no problem yet. But here it comes: One of my Test classes uses the "System.runAs()" with different users to create test opportunities because depending on the user/profile/permission set assigned to the user, some code might execute differently.

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?
11 respuestas
  1. 23 abr 2015, 10:52
    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());

    }

    }

    }

     
0/9000