Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

In the process of writing a unit test on Opportunities, I'm inserting a custom object Journal_c. This custom object, Journal_c, has an after insert trigger associated with it. When running the test, I encounter the following error.

FATAL_ERROR caused by: System.NullPointerException: Attempt to de-reference a null object.

Combing through logs, I've found the offending code to be a SOQL query (shown below) that is producing 0 results and thus the null object.

for ( Contact c : [Select Id, AccountId, Account.Id, Account.Anniversary_Date__c, Account.Member_Since__c, Account.Last_Membership_Date__c, Account.Total_Giving__c, Account.Total_Registration_Payments__c from Contact where Id in :allContactIds and AccountId != null ])

I have tried inserting a Journal__c record through the Salesforce interface and the insert was successful with the above query returning 1 row as a result. Inserting a record as a part of this unit test, however, produces 0 rows and cascades down to the error I mentioned. I have confirmed in both cases that allContactIds set contains a valid contact Id. In fact, it was the same contact Id. What could cause this query to produce different results?

share|improve this question
    
Can you post your test code? There might be an error setting up your test data. –  Mike Chale Jan 24 '13 at 19:46

1 Answer 1

up vote 4 down vote accepted

What's the API version of your unit test and does it have @SeeAllData annotation (which you shouldn't set until you absolutely have to).

You can read a bit more about it here but roughly speaking it's a good idea to create your Account & Contact as a part of setup in the unit test before you actually try to test Journal-related logic. Otherwise the tests might fail in a freshly created Developer Sandbox that doesn't have any data but really it's just a tip of the iceberg ;)

share|improve this answer
    
I added the @SeeAllData annotation and the test passed. I'll remove it, as per your recommendation, and manually insert the account and contacts. Thanks for your help! –  dannymorty Jan 24 '13 at 20:23
2  
Thx and good luck :) Consider making a helper "TestDataFactory" class. It can be annotated @isTest but not have any test methods so it won't count against organization's code limits. You can put there reusable public static methods that create test data for many unit tests. If you need to test governor limits and need a fresh "context" - read about Test.startTest(). –  eyescream Jan 24 '13 at 20:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.