• jp1234
  • NEWBIE
  • 130 Points
  • Member since 2013


  • Chatter
    Feed
  • 4
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 48
    Replies
I am attempting to sort a list based on user clicking columns on visualforce page. Seems like the comparable interface is the best way to do this.

I can sort using static variables but it's messy. I would like to have dynamic variable to compare the list elements; however, I am receiving an error.  Any help is greatly appreciated.

public class loadsort implements Comparable  
    {  
      public parseUtility.load load {get; set;}   
        
      public loadsort(parseutility.load ld)  
      {  
        load = ld;  
      }  
        
      public Integer compareTo(Object VLoad)  
      {  
        loadsort LoadToComp = (loadsort)VLoad;  
        
        if(Load.get(comparefield) > Loadtocomp.load.get(comparefield))  
          return SortOrder.equals('asc') ? 1 : 0;  
        else
          return sortOrder.equals('asc') ? 0 : 1;
      }
    } 

This is the error:::::: Method does not exist or incorrect signature: [ParseUtility.load].get(String)
Hi All, 

I created the Email Handler class below to create a new task on a custom object (User_Support__c). The email will link to the appropriate record by matching the email subject to an auto-number field (Support__c) on the custom object. Unfortunately, I can't get the test method to work. I continually get an error that their are no rows for assignment. Can anyone tell me what I am doing wrong? 


/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailtoSalesForce implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

        String myPlainText= '';
  
  // Add the email plain text into the local variable 
 
  myPlainText = email.plainTextBody;
 
  // New Task object to be created
 
  Task[] newTask = new Task[0];
  {
 
  // Try to lookup any contacts based on the email from address
  // If there is more than 1 contact with the same email address,
  // an exception will be thrown and the catch statement will be called.
  
   User_Support__c vUS = [Select Id, Support__c, Name
    From User_Support__c
    Where Support__c = :email.subject
    Limit 1];
  
  // Add a new Task to the contact record we just found above.
  newTask.add(new Task(Description =  myPlainText,
       Priority = 'Normal',
       Status = 'Completed',
       Type = 'Email',
        Subject = email.subject,
        IsReminderSet = true,
        ReminderDateTime = System.now()+1,
        WhatId =  vUS.Id));
 
 // Insert the new Task 
 insert newTask;
 

                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = vUS.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
    
            }
        }

    result.success = true;
        return result;
    }
    }
}


TEST CLASS
@isTest
private class testusersupportattach{

static testMethod void testMe() {

 Profile p = [Select id from Profile where name = 'GCP'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='ED', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;
  
 
  
User_Support__c us= New User_Support__c(name='attach email to User Support Case',
    Ideal_completion_date__c=System.Today(),
    Request_Type__c='Development',
    Priority_Level__c='Low',
    RecordTypeId='012C0000000I7wx',
    Requested_By__c=u.id);
    
    insert us;
    
    
    
    Test.StartTest();

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

  // setup the data for the email
  email.subject = us.support__c;
  email.fromname = 'FirstName LastName';
  env.fromAddress = u.email;
  

  // call the email service class and test it with the data in the testMethod
  EmailtoSalesForce emailProcess = new EmailtoSalesForce();
  emailProcess.handleInboundEmail(email, env);
Test.StopTest();

  // query for the contact the email service created
  Task Tsk = [select id, Type, status, subject, whatid from Task
    where whatid =:us.id];

  System.assertEquals(Tsk.Subject,us.name);
  System.assertEquals(Tsk.Status,'Completed');
  System.assertEquals(Tsk.Type,'Email');

 
}
}
I new to writing unit test and need to test a visualforce page that implements an extended controller. The visualforce page is called from a custom button on a parent object (Audit__c) that passes an ID for the extended controller. The ID is used to query values on the parent used to render fields on the VF page of the child (Auto_Audit_Sample_Policy__c. )

How do I pass ID's into the unit test ? Also, the parent object (Audit__c) contains several checkbox fields that the child object (Auto_Audit_Sample_Policy__c) queries thru the extended controller. For unit testing do I preset these checkbox values in the test utility class or the actual unit test ? 

This is the error message I am getting:
Error Message    System.QueryException: List has no rows for assignment to SObject
Stack Trace    Class.ParentChildExtensionAUTOsample.<init>: line 27, column 1
Class.UnitTest_Audit.testNewSample: line 37, column 1

The URL for the custom button is:
/apex/PROD_Audit_Auto_PolicySample?AccId={!Audit__c.Id}

The VF page uses the following controller extension:
<apex:page standardController="Auto_Audit_Sample_Policy__c"  extensions="ParentChildExtensionAUTOsample" > 

The extended controller code :
public with sharing class ParentChildExtensionAUTOsample {

/*
This code supports the PROD_Audiit_Auto_PolicySample visualforce page.
FUNCTION:
Receives parent ID (accID) passed via commandbutton or custom button on parent related list.
AccId must be passed via URL since we are instantiating a new object reccord which is not saved.
accID is needed to query parent fields that are used on the visualforce page for rendering.
A non list object is used for the SOQL query to the parent. The result set is used in the visualforce page for setting control variables for rendering. 
* we are always passing the parent ID to this query and using LIMIT=1 per salesforce best practices. 
The parent ID is loaded into the related list field on the instanitated object to establish relationship when saved. 
*/

public Audit__c audit{get;set;}
Auto_Audit_Sample_Policy__c record;

String accId;
@TestVisible private Apexpages.StandardController controller; 

public ParentChildExtensionAUTOsample(ApexPages.StandardController standardController)
{
//set sample to current record.
this.record = (Auto_Audit_Sample_Policy__c)standardController.getrecord();
//grab AccID passed in from URL
accID=ApexPages.currentPage().getParameters().get('AccId');
  
 audit= [SELECT Id, Name, Policy_Information__c, Policy_Number__c, Prior_Carrier__c, Expiring_Premium__c, Reinstatement_Information__c, Insured_Location__c, Agent_Information__c, Agent_City__c, Agent_Name__c, 
    Driver_Information__c, Age__c, Gender__c, Marital_Status__c, Named_Insured_Add_Driver__c, Occupation__c, Business_Use__c, Vehicle_Information__c, Model_Year__c, Vehicle_Type__c, ISO_Symbol__c, 
    Annual_Miles__c, Limit_Information__c, Liability_Limits__c, UM_Limits__c, UIM_Limits__c, UM_UIM_Limits__c, PIP_Limits__c, PIP_Deductible__c, APD_Deductible_Vehicle__c, Premium__c, Rating_Information__c, 
    MVR_Violations__c, Policy_Discounts__c, Rating_Tier__c, Credit_Scoring__c, Telematics_UBI__c, Loss_Information__c, CLUE_Report__c, Prior_Carrier_Loss_Experience__c, Company_Loss_Experience__c, Individual_Loss_Detail__c, 
    General_Information__c, Signed_Application__c, Vehicle_Photo_Information__c, Proof_of_Ownership__c, Other_Policies__c, UW_Guidelines_Followed__c, Risk_Management_Standards__c, Personal_Auto_Product__c      
    FROM Audit__c WHERE Id = :ApexPages.currentPage().getParameters().get('AccId') LIMIT 1];

//Load the parent Name (ID) into the Audit field. 
record.Audit__c = audit.Id;
}
}

Heres my unit test:
 
@isTest
private class UnitTest_Audit {
  //Test coverage for Account Creation
  static testmethod void testGetAccount() {
    Account acct = UtilityAudit.getAccount();
    insert acct;
  }

  //Test coverage for Audit Creation
  static testmethod void testGetAudit() {
    Account acct = UtilityAudit.getAccount();
    insert acct;
    Test.startTest();    
    Audit__c audit = UtilityAudit.getAudit(acct.Id);
    insert audit;
    Test.stopTest();
  }

  //Test coverage for New Audit Sample Creation (VF page) 
  static testmethod void testNewSample() {
    //initiate the VF page
    PageReference pageRef = Page.prod_audit_auto_policysample;
    Test.setcurrentPage(pageref);
      
    Account acct = UtilityAudit.getAccount();
    insert acct;
    Audit__c audit = UtilityAudit.getAudit(acct.Id);
    insert audit; 
    Auto_Audit_Sample_Policy__c sample = UtilityAudit.getAuto_Audit_Sample_Policy(audit.Id);
    insert sample;
		//set required fields
        sample.Policy_Number__c = 'sampleTest';
        sample.Insured_ZipCode__c = '99999';
		
    Test.startTest();    
 
    //create standard controller and extended controller instance    
    ApexPages.StandardController sc = new ApexPages.standardController(sample);
    ParentChildExtensionAUTOsample testPage = new ParentChildExtensionAUTOsample(sc);
    
    Test.stopTest();
  }
}

Heres my utility class for testing:
@isTest
public class UtilityAudit {
    
    //build the Account object
    public static Account getAccount() {
        Account acct = new Account();
        acct.Name = 'Unit Test Account';

        return acct;
    }

    //build the Audit object
    public static Audit__c getAudit(Id accountId) {
        Audit__c audit = new Audit__c();
        audit.Cedent_Account_CCA_PS__c = accountId;
        //set grid checkbox values. Used by Auto Sample to render VF page fields
        audit.Policy_Information__c = true;
        audit.Policy_Number__c = true;
                
        return audit;
    }

    //build the Auto Sample object
    public static Auto_Audit_Sample_Policy__c getAuto_Audit_Sample_Policy(Id AccId) {
        Auto_Audit_Sample_Policy__c samplePolicy = new Auto_Audit_Sample_Policy__c();
        samplePolicy.Audit__c = AccId;
        samplePolicy.Policy_Number__c = 'sampleTest';
        samplePolicy.Insured_ZipCode__c = '99999';
        
        return samplePolicy;
    }    
   
    
}




 
I haven't seen this before and I'm having trouble figuring out why this isn't working. I have a class that handles adding OpportunityContactRoles to an opportunity on create, on account Id change, and on close of an opportunity - the test class for that passes, no issues has been working great for a few years.

I was working on new code that involves updating the opportunity record type, owner, and a few other fields and in some cases cloning the opportunity. My test class for this is failing. The error I'm getting is

System.DmlException: Update failed. First exception on row 0 with id 006180000023YfvAAE; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Upsert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []: []: []

If I turn off the OpportunityContactRoles class I mentioned, my new test class passes 100%. So I've added comments all the way through the contact roles class and I've found that once it hits the upsert statement is what is causing this to happen. 

Is there any particular reason why an opportunity being created using the .clone() method would cause issues with opportunityContactRoles?

Opportunity clonedOpp = opportunity.clone(false, false, true, false);
While I am extracting the profiles, I am not getting full profile meta data rather getting only <loginIpRanges> and <serPermissions> after using ANT migration
Hi all
plz help me in creating a google map containing markers using lat/long fields of account.I was able to do by hard coding values but I want to generate dynamically.
see below code for ref.
<apex:page controller="TestExam">
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["map"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
    
      var lat = [37.4232, 37.4289];
   
  var lon = [-122.0853, -122.1697];

  var data = new google.visualization.DataTable();
  data.addColumn('number', 'lat');
  data.addColumn('number', 'lon');

  for(i = 0; i < lat.length; i++)
    data.addRow([lat[i], lon[i]]);

     
        var map = new google.visualization.Map(document.getElementById('map_div'));
        map.draw(data, {showTip: true});
      }

    </script>
  </head>

  <body>
    <div id="map_div" style="width: 400px; height: 300px"></div>
  </body>
</html>
</apex:page>


I want to fetch lat,lon values from accounts dynamically

 
  • March 28, 2015
  • Like
  • 0
I am getting this error:

Atmember: execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject Class.ATeam_Cls.teamassign: line 66, column 1 Trigger.Atmember: line 2, column 1

class: public class ATeam_Cls {
        
    public static void teamassign(List<Account> newList){
        
        List<AccountTeamMember> latm = new List<AccountTeamMember>();
        List<AccountShare> las = new List<AccountShare>();
        set<id> setids = new set<id>();
        List<User> us = [Select id,userrole.Name,username,Email,profile.name from User where IsActive = true];
        
        for (Account acc : newList) {
            setids.add(acc.id);
        }
        
        List<AccountTeamMember> oldatm = [select id from AccountTeamMember where AccountId in : setids];
        if(oldatm != null){
            delete(oldatm);
        }
        
        for (Account acc : newList) {
        
        ID uid = acc.OwnerId;
        
        for(IDEXX_Water_Territories__c s : IDEXX_Water_Territories__c.getAll().values()){
            
            if(acc.Territory_ID__c == s.Territory_ID__c){ 
                
                for(User u : us){
                
                    if(u.Email == s.User_Email_Address__c ){
        
                        AccountTeamMember atm = new AccountTeamMember();
                        AccountShare  nas = new AccountShare();
                        atm.AccountId = acc.id;                
                        atm.TeamMemberRole = s.TeamMemberRole__c;
                        atm.UserId=u.id; 
                        latm.add(atm);
                        
                        if(u.profile.name != 'System Administrator'){
                         
                            nas.AccountId =acc.id; 
                            nas.UserOrGroupId =u.id;
                            nas.AccountAccessLevel ='Edit';
                            nas.OpportunityAccessLevel = 'Edit';
                            nas.CaseAccessLevel = 'Edit';
                            las.add(nas);
        
                        }
                       
                      
                    }
                }  
            }
        } 
       }
       
        
        try{
            
            insert(las);
            insert(latm);            
            
        }catch(DMLException e){
        
                    system.debug('error on deleting team members ' + e.getMessage());
        } 
        user usr = [select id,name,UserRole.Name from user where id =: userInfo.getUserId()];
    
    for(Account acc : newList){
       AccountTeamMember atm1 = new AccountTeamMember();
    
        atm1.AccountId = acc.id;                
        atm1.TeamMemberRole = usr.UserRole.Name;
        atm1.UserId=UserInfo.getUserId(); 
    
        try{
        
            insert atm1;
        }catch(DMLException e){
        
                    system.debug('error on deleting team members ' + e.getMessage());
        }

    
    }
    }
}

Trigger:

trigger Atmember on Account (after insert,after update) {
    ATeam_Cls.teamassign(trigger.new);
}

above are the class and trigger . please anyone help me out how can it be solved
Hi there... 

1) I have created an apex class in my enterprise salesforce account, and I want to deploy it now to production. So I can use it on my visual force email...

How can I do that? I wouldnt need to test it would I?
 
I am attempting to sort a list based on user clicking columns on visualforce page. Seems like the comparable interface is the best way to do this.

I can sort using static variables but it's messy. I would like to have dynamic variable to compare the list elements; however, I am receiving an error.  Any help is greatly appreciated.

public class loadsort implements Comparable  
    {  
      public parseUtility.load load {get; set;}   
        
      public loadsort(parseutility.load ld)  
      {  
        load = ld;  
      }  
        
      public Integer compareTo(Object VLoad)  
      {  
        loadsort LoadToComp = (loadsort)VLoad;  
        
        if(Load.get(comparefield) > Loadtocomp.load.get(comparefield))  
          return SortOrder.equals('asc') ? 1 : 0;  
        else
          return sortOrder.equals('asc') ? 0 : 1;
      }
    } 

This is the error:::::: Method does not exist or incorrect signature: [ParseUtility.load].get(String)
Hi All, 

I created the Email Handler class below to create a new task on a custom object (User_Support__c). The email will link to the appropriate record by matching the email subject to an auto-number field (Support__c) on the custom object. Unfortunately, I can't get the test method to work. I continually get an error that their are no rows for assignment. Can anyone tell me what I am doing wrong? 


/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class EmailtoSalesForce implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {

        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();

        String myPlainText= '';
  
  // Add the email plain text into the local variable 
 
  myPlainText = email.plainTextBody;
 
  // New Task object to be created
 
  Task[] newTask = new Task[0];
  {
 
  // Try to lookup any contacts based on the email from address
  // If there is more than 1 contact with the same email address,
  // an exception will be thrown and the catch statement will be called.
  
   User_Support__c vUS = [Select Id, Support__c, Name
    From User_Support__c
    Where Support__c = :email.subject
    Limit 1];
  
  // Add a new Task to the contact record we just found above.
  newTask.add(new Task(Description =  myPlainText,
       Priority = 'Normal',
       Status = 'Completed',
       Type = 'Email',
        Subject = email.subject,
        IsReminderSet = true,
        ReminderDateTime = System.now()+1,
        WhatId =  vUS.Id));
 
 // Insert the new Task 
 insert newTask;
 

                if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
      for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
        Attachment attachment = new Attachment();
        // attach to the newly created contact record
        attachment.ParentId = vUS.Id;
        attachment.Name = email.binaryAttachments[i].filename;
        attachment.Body = email.binaryAttachments[i].body;
        insert attachment;
    
            }
        }

    result.success = true;
        return result;
    }
    }
}


TEST CLASS
@isTest
private class testusersupportattach{

static testMethod void testMe() {

 Profile p = [Select id from Profile where name = 'GCP'];


User u = new User(alias = 'mo123', email='mousey.1234@covance.com',
      emailencodingkey='UTF-8', lastname='123', languagelocalekey='en_US',
      localesidkey='en_US', profileid = p.Id, country='United States',
      CVD_Division__c='ED', User_Type__c='AE',
      timezonesidkey='America/Los_Angeles', username='mousey.1234@covance.com');
  insert u;
  
 
  
User_Support__c us= New User_Support__c(name='attach email to User Support Case',
    Ideal_completion_date__c=System.Today(),
    Request_Type__c='Development',
    Priority_Level__c='Low',
    RecordTypeId='012C0000000I7wx',
    Requested_By__c=u.id);
    
    insert us;
    
    
    
    Test.StartTest();

  // create a new email and envelope object
  Messaging.InboundEmail email = new Messaging.InboundEmail() ;
  Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

  // setup the data for the email
  email.subject = us.support__c;
  email.fromname = 'FirstName LastName';
  env.fromAddress = u.email;
  

  // call the email service class and test it with the data in the testMethod
  EmailtoSalesForce emailProcess = new EmailtoSalesForce();
  emailProcess.handleInboundEmail(email, env);
Test.StopTest();

  // query for the contact the email service created
  Task Tsk = [select id, Type, status, subject, whatid from Task
    where whatid =:us.id];

  System.assertEquals(Tsk.Subject,us.name);
  System.assertEquals(Tsk.Status,'Completed');
  System.assertEquals(Tsk.Type,'Email');

 
}
}
I new to writing unit test and need to test a visualforce page that implements an extended controller. The visualforce page is called from a custom button on a parent object (Audit__c) that passes an ID for the extended controller. The ID is used to query values on the parent used to render fields on the VF page of the child (Auto_Audit_Sample_Policy__c. )

How do I pass ID's into the unit test ? Also, the parent object (Audit__c) contains several checkbox fields that the child object (Auto_Audit_Sample_Policy__c) queries thru the extended controller. For unit testing do I preset these checkbox values in the test utility class or the actual unit test ? 

This is the error message I am getting:
Error Message    System.QueryException: List has no rows for assignment to SObject
Stack Trace    Class.ParentChildExtensionAUTOsample.<init>: line 27, column 1
Class.UnitTest_Audit.testNewSample: line 37, column 1

The URL for the custom button is:
/apex/PROD_Audit_Auto_PolicySample?AccId={!Audit__c.Id}

The VF page uses the following controller extension:
<apex:page standardController="Auto_Audit_Sample_Policy__c"  extensions="ParentChildExtensionAUTOsample" > 

The extended controller code :
public with sharing class ParentChildExtensionAUTOsample {

/*
This code supports the PROD_Audiit_Auto_PolicySample visualforce page.
FUNCTION:
Receives parent ID (accID) passed via commandbutton or custom button on parent related list.
AccId must be passed via URL since we are instantiating a new object reccord which is not saved.
accID is needed to query parent fields that are used on the visualforce page for rendering.
A non list object is used for the SOQL query to the parent. The result set is used in the visualforce page for setting control variables for rendering. 
* we are always passing the parent ID to this query and using LIMIT=1 per salesforce best practices. 
The parent ID is loaded into the related list field on the instanitated object to establish relationship when saved. 
*/

public Audit__c audit{get;set;}
Auto_Audit_Sample_Policy__c record;

String accId;
@TestVisible private Apexpages.StandardController controller; 

public ParentChildExtensionAUTOsample(ApexPages.StandardController standardController)
{
//set sample to current record.
this.record = (Auto_Audit_Sample_Policy__c)standardController.getrecord();
//grab AccID passed in from URL
accID=ApexPages.currentPage().getParameters().get('AccId');
  
 audit= [SELECT Id, Name, Policy_Information__c, Policy_Number__c, Prior_Carrier__c, Expiring_Premium__c, Reinstatement_Information__c, Insured_Location__c, Agent_Information__c, Agent_City__c, Agent_Name__c, 
    Driver_Information__c, Age__c, Gender__c, Marital_Status__c, Named_Insured_Add_Driver__c, Occupation__c, Business_Use__c, Vehicle_Information__c, Model_Year__c, Vehicle_Type__c, ISO_Symbol__c, 
    Annual_Miles__c, Limit_Information__c, Liability_Limits__c, UM_Limits__c, UIM_Limits__c, UM_UIM_Limits__c, PIP_Limits__c, PIP_Deductible__c, APD_Deductible_Vehicle__c, Premium__c, Rating_Information__c, 
    MVR_Violations__c, Policy_Discounts__c, Rating_Tier__c, Credit_Scoring__c, Telematics_UBI__c, Loss_Information__c, CLUE_Report__c, Prior_Carrier_Loss_Experience__c, Company_Loss_Experience__c, Individual_Loss_Detail__c, 
    General_Information__c, Signed_Application__c, Vehicle_Photo_Information__c, Proof_of_Ownership__c, Other_Policies__c, UW_Guidelines_Followed__c, Risk_Management_Standards__c, Personal_Auto_Product__c      
    FROM Audit__c WHERE Id = :ApexPages.currentPage().getParameters().get('AccId') LIMIT 1];

//Load the parent Name (ID) into the Audit field. 
record.Audit__c = audit.Id;
}
}

Heres my unit test:
 
@isTest
private class UnitTest_Audit {
  //Test coverage for Account Creation
  static testmethod void testGetAccount() {
    Account acct = UtilityAudit.getAccount();
    insert acct;
  }

  //Test coverage for Audit Creation
  static testmethod void testGetAudit() {
    Account acct = UtilityAudit.getAccount();
    insert acct;
    Test.startTest();    
    Audit__c audit = UtilityAudit.getAudit(acct.Id);
    insert audit;
    Test.stopTest();
  }

  //Test coverage for New Audit Sample Creation (VF page) 
  static testmethod void testNewSample() {
    //initiate the VF page
    PageReference pageRef = Page.prod_audit_auto_policysample;
    Test.setcurrentPage(pageref);
      
    Account acct = UtilityAudit.getAccount();
    insert acct;
    Audit__c audit = UtilityAudit.getAudit(acct.Id);
    insert audit; 
    Auto_Audit_Sample_Policy__c sample = UtilityAudit.getAuto_Audit_Sample_Policy(audit.Id);
    insert sample;
		//set required fields
        sample.Policy_Number__c = 'sampleTest';
        sample.Insured_ZipCode__c = '99999';
		
    Test.startTest();    
 
    //create standard controller and extended controller instance    
    ApexPages.StandardController sc = new ApexPages.standardController(sample);
    ParentChildExtensionAUTOsample testPage = new ParentChildExtensionAUTOsample(sc);
    
    Test.stopTest();
  }
}

Heres my utility class for testing:
@isTest
public class UtilityAudit {
    
    //build the Account object
    public static Account getAccount() {
        Account acct = new Account();
        acct.Name = 'Unit Test Account';

        return acct;
    }

    //build the Audit object
    public static Audit__c getAudit(Id accountId) {
        Audit__c audit = new Audit__c();
        audit.Cedent_Account_CCA_PS__c = accountId;
        //set grid checkbox values. Used by Auto Sample to render VF page fields
        audit.Policy_Information__c = true;
        audit.Policy_Number__c = true;
                
        return audit;
    }

    //build the Auto Sample object
    public static Auto_Audit_Sample_Policy__c getAuto_Audit_Sample_Policy(Id AccId) {
        Auto_Audit_Sample_Policy__c samplePolicy = new Auto_Audit_Sample_Policy__c();
        samplePolicy.Audit__c = AccId;
        samplePolicy.Policy_Number__c = 'sampleTest';
        samplePolicy.Insured_ZipCode__c = '99999';
        
        return samplePolicy;
    }    
   
    
}




 
I haven't seen this before and I'm having trouble figuring out why this isn't working. I have a class that handles adding OpportunityContactRoles to an opportunity on create, on account Id change, and on close of an opportunity - the test class for that passes, no issues has been working great for a few years.

I was working on new code that involves updating the opportunity record type, owner, and a few other fields and in some cases cloning the opportunity. My test class for this is failing. The error I'm getting is

System.DmlException: Update failed. First exception on row 0 with id 006180000023YfvAAE; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Upsert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []: []: []

If I turn off the OpportunityContactRoles class I mentioned, my new test class passes 100%. So I've added comments all the way through the contact roles class and I've found that once it hits the upsert statement is what is causing this to happen. 

Is there any particular reason why an opportunity being created using the .clone() method would cause issues with opportunityContactRoles?

Opportunity clonedOpp = opportunity.clone(false, false, true, false);