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
Savvy AdminSavvy Admin 

"update object.relatedObject__r" caused "Attempt to de-reference a null object" error in Unit Test

Hi all,

The code is working. Just to make it in Production, I need to do proper unit test to make sure the code coverage is above 75%.

In the Controller Extension, I made a simple Page Refence to save the record and it uses "update object.relatedObject__r" to save the related object. Later in the Unit Test, it returns the error saying "Attempt to de-reference a null object". The update line is controlled by condition that when object.relatedObject__c == null, the update line would never be reached.

Therefore, I am sure that the object.relatedObject__c is not null. Then, I thought maybe some fields in the relatedObject are null, which might cause this error. Then I put content in all the fields in the relatedObject. However, the system still returns the error "Attempt to de-reference a null object".

How do I solve this problem? Is there a way to test on the "Update object.relatedObject__r" code?

Thanks a lot.
Best Answer chosen by Savvy Admin
JethaJetha
Hi Savvy,

Please make sure you properly initialized the object record.

if not, please intialise and then use

All Answers

Bhaswanthnaga vivek vutukuriBhaswanthnaga vivek vutukuri
put code and stack trace
JethaJetha
Hi Savvy,

Please make sure you properly initialized the object record.

if not, please intialise and then use
This was selected as the best answer
Savvy AdminSavvy Admin

0down voteacceptSorry guys. I do not paste the code here because the code is too complicated that when you see a small chunk of code you will always want to see the larger picture to explain more. The test involves at least 5 major objects and some other supporting objects, which almost drove me crazy.
Now I am sure that the __r actually represents all the field of that related object. There should be no null field if I want to test on __r. In real execution, there wouldn't be any null field once the record is inserted ('' or 0 is not null). However, in testing, I have to manually add all the fields of that particular object. Further more, I have to focus on the objects structure to make sure the manual generation is correct and logical for the testing. For each of "object" and "relatedObject", I have more than 100 fields...
Anyway, I have sort of solved the problem and the part has been on Production now. I do suggest all testing have an initial function to prepare all the needed objects (although that might be the most complicated part in the unit test). If it is possible, I hope in the near future Salesforce can provide something like record generator for unit test usage.