Test Slack Apps

Write unit tests to verify whether your Apex code is working properly. Unit tests are class methods that don't take arguments or commit data to the database.

Slack app testing includes several files.

  • The Apex class to be tested
  • The Apex unit tests
  • ApexClass metadata file
  • ApexTestSuite metadata file

In your SFDX project, create an Apex unit test in the classes folder.

|_ classes/
    |_ MyAction.cls
    |_ MyAction.cls-meta.xml
    |_TestMyAction.cls
    |_TestMyAction.cls-meta.xml
|_ slackapps/
|_ testSuites/
    |_MyActionTestSuite.testSuite-meta.xml
|_ viewdefinitions/

Write a Test

Create a test class and annotate it with @isTest. Similarly, annotate your class methods with @isTest.

Name your test class using the format TestYourActionName, like TestAppHomeOpened or TestCreateRecordDispatcher.

Declare your test harness variables to store the Slack state and user session. To set up your test harness and simulate user interactions, use the Slack.TestHarness class.

@isTest
public class TestMyAction {

  // Test harness variables
  private static Slack.App slackApp;
  private static Slack.TestHarness testHarness;
  private static Slack.TestHarness.State slackState;
  private static Slack.TestHarness.UserSession userSession;

  static {
      // Set up test harness and user session
      slackApp = Slack.App.ApexSlackApp.get();
      testHarness = new Slack.TestHarness();
      slackState = testHarness.getNewSlackState();
      userSession = slackState.createUserSession();
  }

   // Methods for testing
   @isTest static void test1() {
      // Implement test code
   }

   @isTest static void test2() {
      // Implement test code
   }

}

tip: For more information, see Testing Examples.

Add the ApexClass Metadata File

The ApexClass metadata file represents an Apex class, which you include for each test class.

TestMyAction.cls-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <status>Active</status>
</ApexClass>

Add the ApexTestSuite Metadata File

The ApexTestSuite metadata file represents a suite of Apex test classes to include in a test run.

MyActionTestSuite.testSuite-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<ApexTestSuite xmlns="http://soap.sforce.com/2006/04/metadata">
    <testClassName>TestMyAction</testClassName>
    <testClassName>TestMyOtherAction</testClassName>
</ApexTestSuite>

See Also

What Are Apex Unit Tests?