[SalesForce] Assign a case to a queue in Apex (Test class)

I'm sure this must be quite possible, and probably easy.

I need to create a test method in which part of the scenario is that for when a Case is assigned to a Queue. I have successfully tested all my scenarios where Cases are owned by Users, but I cannot work out how to programmatically assign my test case to a queue.

The core of my test method currently creates a test queue and (simplified snippet) sticks a case in, owned by this queue; like so:

Group testGroup = new Group(Name='test group', type='Queue');
insert testGroup;

QueuesObject testQueue = new QueueSObject(QueueID = testGroup.id, SobjectType = 'Case');
insert testQueue;

Case aCase = new Case(OwnerId = testQueue.Id);

Insert aCase;

This then goes on to do a load of testing, but when I run the test, I get the error message:

Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Owner ID: id value of incorrect type: 03gf00000001X2RAAU: [OwnerId]

On the insert of the case.

Now, we know Cases can be owned by Users or Queues (snippet here from the case field list)

case owner field

but apparantly, this Id cannot be set to a Queue? (and you cannot directly set the Owner field, you get a "Field is not writeable" error at compile time).

Can someone help me out here? Cheers.

Best Answer

Rather than setting the Case.OwnerId to the Queue ID you need to set it to the Group ID. As OwnerId is a lookup to User and Group rather than User and Queue as displayed in the UI.

You can check it yourself using Workbench > Info > Standard & Custom Objects > Case, Fields > OwnerId > Reference To.

Workbench

However by doing this you will receive a MIXED_DML_EXCEPTION due to executing DML on a setup object (inserting QueuesObject) between DML on non-setup objects (Group and Case) to get around this you need to execute the DML on setup objects in a different context, this can be done using System.runAs(...).

If you change it to the following it should work:

Group testGroup = new Group(Name='test group', Type='Queue');
insert testGroup;

System.runAs(new User(Id=UserInfo.getUserId()))
{
    QueuesObject testQueue = new QueueSObject(QueueID = testGroup.id, SObjectType = 'Case');
    insert testQueue;
}

Case aCase = new Case(OwnerId = testGroup.Id);
insert aCase;
Related Topic