I followed the steps to use runAs but it is still giving me a mixed_dml exception. I need to populate the contactId so the user has to have a portal profile. Here's what I have for the test method thus far and it is failing with Mixed_DML:
static testMethod void shouldUpdateRollupStatusAndUserRecordWithoutMixedDMLException()
{
//Create portal account owner
UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
User portalAccountOwner1 = new User(
UserRoleId = portalRole.Id,
ProfileId = profile1.Id,
Username = System.now().millisecond() + '[email protected]',
Alias = 'batman',
Email='[email protected]',
EmailEncodingKey='UTF-8',
Firstname='Bruce',
Lastname='Wayne',
LanguageLocaleKey='en_US',
LocaleSidKey='en_US',
TimeZoneSidKey='America/Chicago'
);
Database.insert(portalAccountOwner1);
//Create account
Account portalAccount1 = new Account(
Name = 'TestAccount',
OwnerId = portalAccountOwner1.Id
);
Database.insert(portalAccount1);
//Create contact
Contact contact1 = new Contact(
FirstName = 'Test',
Lastname = 'McTesty',
AccountId = portalAccount1.Id,
Email = System.now().millisecond() + '[email protected]'
);
Database.insert(contact1);
User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
System.runAs ( thisUser ) {
//Create user
Profile portalProfile = [SELECT Id FROM Profile WHERE Name LIKE '%Portal User%' Limit 1];
User user1 = new User(
Username = System.now().millisecond() + '[email protected]',
ContactId = contact1.Id,
ProfileId = portalProfile.Id,
Alias = 'test123',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'McTesty',
CommunityNickname = 'test12345',
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US'
);
Database.insert(user1);
}
}