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
Ram ArzaRam Arza 

System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)

Hello,

I am trying to insert a profile called "Vendor Partner Portal" for a user in my test class. When I run the tests I am getting an error message saying  System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object: Product_Line__c: []

Stack Trace: Class.Test_salesQuotes.runasPartner: line 230, column 1
Below is my code. Can someone help me find what the issue is
 
@isTest()
public class Test_salesQuotes{
public static testmethod void method1(){

//Method 1
      // To begin, the sample application first creates the necessary records
      // to test OpportunityLineItems: Pricebook2, Product2, and PricebookEntry
      // First it creates a product with a standard price
      Product2 p = new product2(name='gack',isActive=true);
      insert p;
      Id pricebookId = Test.getStandardPricebookId();
      
      try{
        insert new PricebookEntry(pricebook2id = pricebookId, product2id = p.id, 
                                unitprice=1.0, isActive=true);
      }catch(System.DMLException e){
        //Swallow exception.. Trigger should have already created the Standard PB entry for this product.
      }
      
      // Next, it creates a new pricebook with an entry for this product
      Pricebook2 pb = new pricebook2(name='test', Ext_Ref_Id__c='asldfjlakjsdf234234');
      insert pb;
      PricebookEntry pbe = new PricebookEntry(pricebook2id=pb.id, product2id=p.id, 
                                              unitprice=1.0, isActive=true);
      insert pbe;
      // To test the first example from the sample application, the test
      // method creates an opportunity line item using the pricebook entry,
      // and then asserts that the Color field was correctly copied from the
      // product after record insertion.
      Opportunity o = new Opportunity(name='test', pricebook2id=pb.id,
      stageName='Open', CloseDate=Date.newInstance(2006,10,10));
      insert o;
      OpportunityLineItem oli = new OpportunityLineItem(opportunityid=o.id, 
                                pricebookentryid=pbe.id, unitprice=1.5, quantity=2);
      insert oli;
    
      // To test the fifth example from the sample application, the test method
      // creates a primary quote and then asserts that its Primary field cannot
      // be deselected. The code uses the try...catch testing idiom to assert
      // that the error message is correct.
      SFDC_520_Quote__c q = new SFDC_520_Quote__c(opportunity__c = o.id, primary__c = true);
      insert q;    
}

//Method2
  
  static testmethod void t1() {
    SFDC_520_Quote__c q = new SFDC_520_Quote__c(); 
    insert q; 
    salesQuotes s = new salesQuotes( new ApexPages.StandardController(q ) );
          
  }

//Method3
   public static  testMethod  void test1() {
      Product_Line__c pl = new Product_Line__c(name = 'myPL');
      insert pl;     

     Product2 p = new product2(name='gack',family='gack',productcode='gack',Product_Line__c=pl.Id,isActive=true);
      insert p;
       
       Product2 p3 = new product2(name='gack',family='gack',productcode='gack',Product_Line__c=pl.Id,isActive=true);
       p3.Loanable__c=true;
      insert p3;
      
      Id pricebookId = Test.getStandardPricebookId();
      
      try{
          insert new PricebookEntry(pricebook2id = pricebookId, product2id = p.id, 
                                unitprice=1.0, isActive=true);
      }catch(System.DMLException e){
        //Swallow exception - creating the product2 should have created a standard 
        //PricebookEntry already.
      }    
        // Next, it creates a new pricebook with an entry for this product
        Pricebook2 pb = new pricebook2(name='test', Ext_Ref_Id__c='asldfjlakjsdf234234');
        insert pb;
        PricebookEntry pbe = new PricebookEntry(pricebook2id=pb.id, product2id=p.id, 
                                              unitprice=1.0, isActive=true);
        insert pbe;
               
        Opportunity o = new Opportunity(name='test', pricebook2id=pb.id,
        stageName='Open', CloseDate=Date.newInstance(2006,10,10));
        insert o;
        OpportunityLineItem oli = new OpportunityLineItem(opportunityid=o.id, 
                                pricebookentryid=pbe.id, unitprice=1.5, quantity=2);
        insert oli;
        
    SFDC_520_Quote__c q = new SFDC_520_Quote__c(Opportunity__c = o.id); 
    insert q;
     
     id VendorPQRecordType = [select Id FROM RecordType where Name = 'Primary Cells Request'].Id;
       
      SFDC_520_Quote__c q1 = new SFDC_520_Quote__c(Opportunity__c = o.id); 
      q1.recordtypeid=VendorPQRecordType;
     insert q1; 
    
    PageReference pageRef = Page.AddQuoteLines;
        Test.setCurrentPage(pageRef);
      system.debug( 'quote id is '+q.id);
      
      ApexPages.currentPage().getParameters().put('id', q.id);
      
     salesQuotes s = new salesQuotes();
     ApexPages.currentPage().getParameters().put('reloadQuote','1');
       
     ApexPages.currentPage().getParameters().put('id', q1.id);
      
     salesQuotes s1 = new salesQuotes();
     ApexPages.currentPage().getParameters().put('reloadQuote','1');
       
     ApexPages.currentPage().getParameters().put('userTypeName', null);
       
     system.assertEquals('Standard',s1.UserTypeName);
     
     s1.CopyOperation(); 
     s.CopyOperation();
     
     s.save(  ) ;
     system.debug ( s.total );
     
     ApexPages.currentPage().getParameters().put('pid', p.id);
     s.enableAddProducts();
     s.searchStr='g';
     s.doSearch(); 
     Id [] fixedSearchResults= new Id[1];
         fixedSearchResults[0] = p.id;
         Test.setFixedSearchResults(fixedSearchResults);
     
     s.searchStr = 'gac';
     s.sortField = 'Product_Line__c';
     s.doSearch();
     
     try { s.addProd();
       // search does not find products inserted by test?
     } catch( System.NullPointerException npe) {
     }
     
     s.copyAndEdit();
 //  s.queryQuoteLines( s.quote.id); 
     s.recalc();
     
     s1.copyLineItemsFromQuoteToOppty();
       
     Account acct = test_standardobjectutil.createAccount('Test Account', false);
    // acct.IsPartner=true;
     insert acct;
       
     Contact c = test_standardobjectutil.createContact('John','Doe2', false);
     c.accountid = acct.Id;
     insert c;                  
   }

    /* Method 4*/
    
    public static  testMethod  void runasPartner() {
         
         Product_Line__c pl = new Product_Line__c(name = 'myPL');
      insert pl;     

     Product2 p = new product2(name='gack',family='gack',productcode='gack',Product_Line__c=pl.Id,isActive=true);
      insert p;
       
       Product2 p3 = new product2(name='gack',family='gack',productcode='gack',Product_Line__c=pl.Id,isActive=true);
       p3.Loanable__c=true;
      insert p3;
  Id pricebookId = Test.getStandardPricebookId();     
      try{
          insert new PricebookEntry(pricebook2id = pricebookId , product2id = p.id, 
                                unitprice=1.0, isActive=true);
      }catch(System.DMLException e){
        //Swallow exception - creating the product2 should have created a standard 
        //PricebookEntry already.
      }
      
        Pricebook2 pb = new pricebook2(name='test', Ext_Ref_Id__c='asldfjlakjsdf234234');
        insert pb;
        PricebookEntry pbe = new PricebookEntry(pricebook2id=pb.id, product2id=p.id, 
                                              unitprice=1.0, isActive=true);
        insert pbe;
     
       Opportunity o = new Opportunity(name='test', pricebook2id=pb.id,
        stageName='Open', CloseDate=Date.newInstance(2006,10,10));
        insert o;
        OpportunityLineItem oli = new OpportunityLineItem(opportunityid=o.id, 
                                pricebookentryid=pbe.id, unitprice=1.5, quantity=2);
        insert oli;
        
     SFDC_520_Quote__c q = new SFDC_520_Quote__c(Opportunity__c = o.id); 
    insert q;
   
      id VendorPQRecordType = [select Id FROM RecordType where Name = 'Primary Cells Request'].Id;
        
       SFDC_520_Quote__c q1 = new SFDC_520_Quote__c(Opportunity__c = o.id); 
         q1.recordtypeid=VendorPQRecordType;
     insert q1;
     
    PageReference pageRef = Page.AddQuoteLines;
        Test.setCurrentPage(pageRef);
      system.debug( 'quote id is '+q.id);
      
      ApexPages.currentPage().getParameters().put('id', q.id);
      
     salesQuotes s = new salesQuotes();
     ApexPages.currentPage().getParameters().put('reloadQuote','1');
       
     ApexPages.currentPage().getParameters().put('id', q1.id);
      
     salesQuotes s1 = new salesQuotes();
     ApexPages.currentPage().getParameters().put('reloadQuote','1');
       
     ApexPages.currentPage().getParameters().put('userTypeName', null);
       
     system.assertEquals('Standard',s1.UserTypeName);
     
        Account acct = test_standardobjectutil.createAccount('Test Account', false);
    // acct.IsPartner=true;
     insert acct;
       
     Contact c = test_standardobjectutil.createContact('John','Doe2', false);
     c.accountid = acct.Id;
     insert c;  
     
     Profile userProfile = [SELECT Id FROM Profile WHERE Name='Vendor Partner Portal']; 
     User u = new User(Alias = 't23', Email='teststandarduser@stemcell.com', 
     EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
     LocaleSidKey='en_US', ProfileId = userProfile.Id,
     ContactId = c.id,
     TimeZoneSidKey='America/Los_Angeles', UserName='teststandarduser@stemcell.com');
     insert u;
        system.runAs(u){
            
            ApexPages.currentPage().getParameters().put('pid', p.id);
             s.enableAddProducts();
             s.searchStr='g';
            system.debug('Test exact user:'+ u); 
            s.doSearch(); 
        }
   }
   }

 
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Ram,
May I request you to please refer the below link for reference. Hope it will be helpful.

Best Regards
Rahul Kumar
Ram ArzaRam Arza
Hey Rahul,  that's exactly what I did right. Inserted an user first then tried to use system.runAs(). Can you please eloborate what exactly did you want to refer from the link.