Why are my test classes failing while creating 2GP package creation?

Problem

Deploying Salesforce 2GP managed packages can be streamlined, but unexpected test class failures during the BETA package creation phase are a common situation. These failures often halt deployments and require significant debugging time – potentially impacting project timelines and resources.

This is a bit interesting situation – as you can’t debug your TEST RUNS while running a packaging command.

The solution?

Leverage ASSERT messages. These custom assertions act as a powerful debugging utility, providing detailed insights into the cause of test failures specifically during the packaging process.

First make sure you are using latest CLI packages required. When TEST classes fail, the give you the ASSERT message that you have defined. These message can be used as a DEBUG utility when you have such PACKAGING situations. The test executes in a SYSTEM MODE until you specify RUN AS for a profile specific use cases. Using ASSERT messages to debug lead to me a default behavioral change in latest packaging process. Yes, the SECURITY enforcements at FIELD LEVEL still trigger even if the TEST is not run in a specific user context. That is a good security process upgrade.

I had this permission set which was around the Custom Objects & it’s fields. Instead of making changes in the TEST class – I assigned the permission set to TEST execution?

YES, you can specify permission sets to use while packaging test execution for it’s default user context without touching the TEST CLASSSES. The permission sets get auto-assigned during package creation with CODE COVERAGE enabled. Specify the permission sets for packaging TEST using below property in sfdx-project.json file’s projectDirectories setup.

Quick recap to troubleshoot this situation:

  • SF CLI Version: Ensure you’re using the latest SF CLI.
  • Dependencies & Directory: Verify all required objects and dependencies are included in your working directory. Use sf doctor for dependency checks or installation issues.
  • Local Test Execution: Confirm that your test classes run successfully on a local scratch org before packaging.
  • Permissions: Ensure the correct permissions set/profile is assigned to allow TEST execution during package creation (with CODE COVERAGE enabled). Also make sure you are using RUN AS as per your security use cases.

Have a great day ahead.