Salesforce Certified Application Architect

Thursday 2 January 2014

Mixed DML Operations in Test Methods

Test methods allow for performing mixed DML operations between the sObjects listed in sObjects That Cannot Be Used
Together in DML Operations and other sObjects if the code that performs the DML operations is enclosed within
System.runAs method blocks. This enables you, for example, to create a user with a role and other sObjects in the same
test.

===========================================================================================
Hi All,

Here is the syntax to avoid test class errors in Mixed DML Operation salesforce,


@isTest
public class MyTest
{
  Public static testmethod void Test_MyTest()
   {
      User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
      System.runAs (thisUser) 
      {
      
    // Add your test class content here
     }
   }
}

=========================================================================================
Example:

@isTest
private class RunasTest {
static testMethod void mixeddmltest() {
// Create the account and group.
Account ac = new Account(Name='TEST ACCOUNT');
// Group is created in the insert trigger.
insert ac;
// Set up user
User u1 = [SELECT Id FROM User WHERE UserName='testadmin@acme.com'];
System.RunAs(u1){
// Add startTest and stopTest to avoid mixed DML error
Test.startTest();



No comments:

Post a Comment

Salesforce Certified Application Architect & Certified Data Architecture and Management Designer Exam

How to pass Salesforce Certified Data Architecture and Management Designer Exam This exam was 1st architect exam for me. Its not that muc...