[SalesForce] How to setup test data for Omni-Channel in Apex Test Classes

I am using UserServicePresence object in Apex to retrieve the user status on Omni-Channel and I get the users to perform further logic. It works fine.

Apex Class code snippet:

//Get the users who have the Omni Channel Status as online
List<UserServicePresence> onlineStatusList = [ select Id,UserId from UserServicePresence where IsCurrentState = true  and ServicePresenceStatus.DeveloperName = 'online' ];

if(onlineStatusList != null && onlineStatusList.size() > 0)
{
    // do some stuff here
}

However, I am not able to find a way to setup the test data for the UserServicePresence object in my test class in order to get the required test coverage. The UserServicePresence object is not writeable and it won't allow us to insert any test records in to it. So, whenever I test the class, the onlineStatusList would always have 0 rows. And there is a major portion of my code inside the if block which I am not able to cover using the test class.

Please let me know if there is a way to test out the Omni-Channel status in the Apex test classes.

Best Answer

I've got the same problem and I solved it using Test.isRunningTest() in the if condition. So you can do something like this:

if((onlineStatusList != null && onlineStatusList.size() > 0) || 
Test.isRunningTest())

It's not a "clean" solution but it works.

Related Topic