[SalesForce] Owner is null after insert – Test class

I have to test the results of a query like this:

[SELECT Id, Owner.Name FROM MyObject__c]

which is called in the constructor of a visualforce page. The Owner.Name is diplayed in the page. The page works fine and I can read the names.

In the unit test though…

User u = [SELECT Id, Name From User..]; //some User
System.runAs(u){
    testObj = new MyObject__c(Field__c='test',OwnerId=u.Id);
    insert testObj;
}

/*
..test goes on, the contructor of the page is called and finally the query arrives:
*/

MyObject o = [SELECT Id, Owner.Name, OwnerId FROM MyObject__c WHERE..]

//o.OwnerId = correct Id
System.assertEquals(u.Id, o.OwnerId); //ok


//o.Owner = null
//o.Owner.Name = null
//...how does this work?
System.assertEquals(u.Name, o.Owner.Name); //not ok

Any insight?

Thank you very much.

Best Answer

salesforce known bug :

None of the owner fields are accessible in a test class

https://success.salesforce.com/issues_view?id=a1p30000000SwHDAA0

Interesting fact 1: when you use myobject.ownerid assertion passed but when you do myobject.owner.id assertion fails

System.AssertException: Assertion Failed: Expected: 005d0000001U4iVAAS, Actual: null

Interesting fact 2: field name typo in the bug heading :P

While Using SeeAllData=false, owner filed not visible in SOQL on Custom Objects