[SalesForce] Test Class – Error: Compile Error: Field is not writeable: Opportunity.ConnectionReceivedId

I have a re-parenting trigger that fires if the connectionReceivedId is of a certain value. The sad part is that it looks like that field is not writeable, so testing is not possible. I know I could rewrite the trigger to work around this, but I would enjoy being able to actually sort records needing re-parenting by the connection from which they were received.

@istest
public class reparenttestclass{
static testmethod void reparenttestclassmethod(){

Opportunity testopp = new Opportunity(
name = 'testopp', recordTypeId = 'xxxxxxxxxx', connectionReceivedId = 'testconnid', AccountId = 'xxxxxxxxxxx', CloseDate = Date.newInstance(2009, 3, 11), StageName = 'testopp');
insert testopp;

Account testacct = new Account(
name = 'testacct');
insert testacct;

}}

Best Answer

To test things like this, I create a class that mimics the object. During the test I deserialize the class into a list of those objects. In the code that the trigger calls, I check for a static test property to be true and if so then get the test objects instead of database object. It allows you to test the functionality of that piece (sorting, etc) while being able to control the testing of actual database records for other tests.

An example (a bit abstract) of how to deserialize a class to get an sObject that can be used in your code:

Public class parentClassTest{
  public static useTestObject = false;

  public static test method void doTest(){
        useTestObject = true;

        //insert records to cause trigger to fire
  }

  public static Opportunity[] getTestOpps(){
      mytestClass[] tmp = new MyTestClass[]{};
      //populate with records
      return (Opportunity[])json.deserialize(json.serialize(New myTestClass()),List<Opportunity>.class);
  }
public class myTestClass{

    public id id {get;set;}
    public String name {get;set;}
    public Id connectionReceivedId {get;set;}

    public mytestClass(){
        name = 'test';
    }

}

In your code you would:

Opportunity[] o = parentClassTest.useTestObject ? parentTestClass.getTestOpps() : TRIGGERVALUES;