function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
snippets@sfsnippets@sf 

Test Class Mock User

Hi , Can we create a mock user for testclass along with the Role 

 

For Eg: 'Custom Profile' with 'Manager Role'

 

I am able to retrive both Profile id and role id. of which assining it to the new users respective Field.

 

But i am unable to get the user Created as it Throws an MIXED_DML_OPERATION.

 

also tried with the workaround from Blogs to use @future annotation. by this it excecutes fine but dose not asign the role in the Context.

 

Please leme know if i am missing anything.

Best Answer chosen by Admin (Salesforce Developers) 

All Answers

Imran MohammedImran Mohammed

Can you post the code, so that I/someone can see that and provide a solution?

snippets@sfsnippets@sf

Hi Imran Bhai,

Thanks for the reply,

below is the snippet.

Inside Test class
---
---
static User createMockUser(Id profileId ,Id Roleid) {
          User u = new User(alias = 'TestUser', email='p***n.m****l@***.com',
          emailencodingkey='UTF-8', lastname='Testing', 
          languagelocalekey='en_US', localesidkey='en_US', profileid = profileId,UserRoleId=Roleid,
          timezonesidkey='America/Los_Angeles', username= System.now().millisecond() + 'p***n.m****l@***.com');
          insert u;
          return  u; 
      }
    static User createMockUserForProfileAndRole(String profileName,String RoleName) {
       Profile p = [SELECT Id FROM profile WHERE name like :profileName limit 1];
       UserRole ur =[SELECT Name, DeveloperName from UserRole WHERE Name=:RoleName LIMIT 1];

       return createMockUser(p.id,ur.id);
     } 
static testMethod void testMe(){
createMockUserForProfileAndRole('CustomProfile','Manager');
}

---

 

snippets@sfsnippets@sf

Any  clue...

sfdcfoxsfdcfox
This was selected as the best answer
snippets@sfsnippets@sf

Hi, @sfdcfox you saved me.

I got to know with link you shared that Mixed DML Operations can be performed with the System.RunAs();

 

Thats exactly what i was looking for.

 

Thanks.