+ Start a Discussion

Relationship in query is null in Apex test method

I'm trying to write some tests for a Visualforce controller extension, however the tests are failing because a query in the controller is not retrieving related sObjects in a query. Outside of testing (in the sandbox), the related sObjects are retrieved without issue, but in testing the related sObjects are null.


Here is the query code in the controller:

private void queryRel ()
	for (Relationship__c r : [SELECT Id,Name,Primary_Client__r.Name,Owner.Id,Owner.Name,Owner.IsActive FROM Relationship__c WHERE Id = : relId FOR UPDATE])
		rel = r;

 In the test environment, Owner is null.


Here is the setup code for the test:

List<Relationship__c> rList = [SELECT Id,OwnerId,(SELECT Id FROM Accounts__r) FROM Relationship__c];
rList[2].OwnerId = [SELECT Id FROM User WHERE IsActive = TRUE AND Id != : UserInfo.getUserId() LIMIT 1].Id;

ApexPages.StandardController sc = new ApexPages.StandardController([SELECT Id FROM Relationship__c WHERE Id = : rList[0].Id]);
RelationshipAddController rac = new RelationshipAddController(sc);
System.AssertNotEquals('fatal',rac.pageMsgSeverity,rac.pageMsgBody + rac.rel);

 Currently that first assertion fails because an internal check to verify the Owner is active fails since Owner.IsActive is null.


Any suggestions would be greatly appreciated.

It also occurred to me that I encountered this exact problem earlier in this same project, I just worked around it.

Both instances, a related query to Owner returned null. So far this has only happened when querying Owner as a related field (other related queries execute properly). Is this a built-in limitation I haven't come across before or is it a bug?
Ritesh AswaneyRitesh Aswaney

are you creating your own test data - if not, the data in the sandbox will not be visible to your test.

if you want your tests to have visibility of the test  data, use the annotation @isTest (SeeAllData = true)

Yes, the test data is created in the test method.