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
V100V100 

Test Class using ReportsTo

I amtrying to write a test class for Contacts code with ReportsTo completed

The code creates a single contact (ignore the test factory piece) and then creates a second contact reporting to the first.

The first and second contacts are created, but the ReportsTo is null on the second.

Contact con1 = Test_Factory.CreateContact();
con1.AccountId = tt.testADP.Customer__c;
con1.Contact_Post_Code__c = 'WR5 3RL';
insert con1;
Contact con2 = Test_Factory.CreateContact();
con2.AccountId = tt.testADP.Customer__c;
con2.Contact_Post_Code__c = 'WR5 3RL';
con2.ReportsTo = con1;

 I have tried the variationbut that no longer works

con2.ReportsToId = con1.Id;

There was a similar issue raised:

http://boards.developerforce.com/t5/Apex-Code-Development/Trigger-not-updating-Contact-RelatedTo-field-with-no-reason-why/m-p/209732/highlight/true#M37146

That shows a work around, however this is for a test class so cannot really work around.

Are there problems writing to this field via Apex or have a i got something wrong.

Any help much appreciated.

Best Answer chosen by Admin (Salesforce Developers) 
BritishBoyinDCBritishBoyinDC

This works for me...

 

@isTest
private class bfctest_ignore {

    static testMethod void myUnitTest() {
        Contact con1 = new Contact(LastName = 'Con1');
con1.AccountId = '001W0000001QbDg';
con1.MailingPostalCode = 'WR5 3RL';
insert con1;
Contact con2 = new Contact(LastName = 'Con2');
con2.AccountId = '001W0000001QbDg';
con2.MailingPostalCode = 'WR5 3RL';
con2.ReportsToId = con1.Id;
insert con2;

Contact testcon = [Select Id, ReportsToId from Contact where Id = :con2.Id];
system.assertequals(con1.Id, testcon.ReportsToId);

    }
}

 

All Answers

BritishBoyinDCBritishBoyinDC

This works for me...

 

@isTest
private class bfctest_ignore {

    static testMethod void myUnitTest() {
        Contact con1 = new Contact(LastName = 'Con1');
con1.AccountId = '001W0000001QbDg';
con1.MailingPostalCode = 'WR5 3RL';
insert con1;
Contact con2 = new Contact(LastName = 'Con2');
con2.AccountId = '001W0000001QbDg';
con2.MailingPostalCode = 'WR5 3RL';
con2.ReportsToId = con1.Id;
insert con2;

Contact testcon = [Select Id, ReportsToId from Contact where Id = :con2.Id];
system.assertequals(con1.Id, testcon.ReportsToId);

    }
}

 

This was selected as the best answer
V100V100

and me too, not sure where i went wrong though, but thanks :-)