Using some very simple Apex code:

Case c = new Case();
insert c;

The OwnerId property on the case is always null. I've even tried running the test as a specific user using System.runAs, but that yields the same result.

Is there a way to set the owner property in test methods? Ultimately my test case needs to test sending an e-mail to the case owner, so if I can't set the owner there's little value in creating my unit test.

  • How are you testing the OwnerId? Are you testing c.OwnerId directly or retrieving the case with SOQL?
    – Rob
    Sep 2 '15 at 16:23
  • @Rob I create and insert the case. I then create and insert an attachment (the attachment ParentId is set to be related to the case). My code eventually queries the case via SOQL. Sep 2 '15 at 16:24
  • You can assign the Owner to the runAs or any other user that you create for the test. If you also create an Account (good practice), you can assign it to the account.OwnerId by creating a User that owns the account, etc.
    – crmprogdev
    Sep 2 '15 at 16:26

Not sure at what point you are checking the OwnerID so taking a shot at an example that works and you can refactor from there

This example test works just fine in several of my sandbox orgs:

private class exampleTest{

    private static testmethod void basic(){

        Account a = New Account(Name = 'Test');
        insert a;

        a = [Select OwnerID, Owner.ID From Account where ID = :a.id];



You may have to adjust the account fields.

Important to note: You must query for the record after creating it before checking the value to get the updated values.

This works for Case:

private class exampleTest{

    private static testmethod void basic(){

        Case c = New Case();
        insert c;

        c = [Select OwnerID, Owner.ID From Case where ID = :c.id];



NOTE: Owner.id will always return null


The OwnerId gets set but after the case is committed to the database, so you would need to query it back.
E.g. In the test class below, c1.OwnerId will be null but c2.OwnerId will not.

private class TestOwnerId{

    static testmethod void test1(){
        Case c1 = new Case();
        insert c1;

        system.debug('c1.OwnerId: ' + c1.OwnerId);

        Case c2 = [Select OwnerId From Case where Id = :c1.Id];
        system.debug('c2.OwnerId: ' + c2.OwnerId);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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