Salesforce Messaging Session record in Apex Test Class

Salesforce Messaging Session record in Apex Test Class

The following sample Apex code is only for Standard Channel. I have used MessageType as ‘Text’. So, it is for SMS Channel.

Sample Apex Code:

/**
 * @description Test class for MessagingSession functionality.
 * This class contains test methods to ensure the correct creation and
 * handling of MessagingSession records.
 * @author Magulan Duraipandian
 * @date 2024-07-02
 */
@isTest
private class MessagingSessionTest {

    /**
     * @description Test method to verify the creation of a MessagingSession
     * and its associated records (MessagingChannel and MessagingEndUser).
     * It runs as a specific user to ensure proper permissions and context.
     * @param No parameters
     * @return void
     */
    testMethod static void testMessagingSession() {

        // Query the current user to run the test as.
        User thisUser = [
            SELECT Id
            FROM User
            WHERE Id = :UserInfo.getUserId()
        ];

        System.runAs ( thisUser ) {
            // Create a test MessagingChannel record.
            MessagingChannel objMsgChannel = new MessagingChannel();
            objMsgChannel.MasterLabel = 'TestChannel';
            objMsgChannel.DeveloperName = 'TestChannel';
            objMsgChannel.IsActive = true;
            objMsgChannel.MessageType = 'Text';
            objMsgChannel.MessagingPlatformKey = 'TestChannel';
            insert objMsgChannel;

            // Create a test MessagingEndUser record associated with the channel.
            MessagingEndUser objMsgUser = new MessagingEndUser();
            objMsgUser.Name = 'Messaging User';
            objMsgUser.MessagingChannelId = objMsgChannel.Id;
            objMsgUser.MessageType = 'Text';
            objMsgUser.MessagingPlatformKey = 'TestChannel';
            insert objMsgUser;

            // Create and insert the MessagingSession, linking it to the end user and channel.
            MessagingSession objSession = new MessagingSession();
            objSession.MessagingEndUserId = objMsgUser.Id;
            objSession.MessagingChannelId = objMsgChannel.Id;
            objSession.Status = 'New';
            insert objSession;

            // Debug statement to confirm the session was created.
            System.debug(
                'Id of the Messaging Session is ' +
                objSession.Id
            );
        }

    }

}

Use MessageType = ‘EmbeddedMessaging’ for Enhanced Chat(Messaging for In-App and Web). MessageType = ‘Text’ is for SMS Channels.

Leave a Reply