3

I've recently added some Field Level Security checks into the Apex code of a 2GP managed package.

But when I run:

sfdx force:package:version:create ...

A lot of the tests fail, saying the fields are not createable.

I found this question:

Which mentions

this command takes what you have in your local source folder and then uses via the DevHub org spins up a transient scratch org and checks the metadata deploys there.

Therefore, I assume the user running the tests does not have access to the fields via the Permission Set which is included in the package.

I tried adding a InstallHandler but it doesn't get run, because it is not a package yet.

I cannot include a modified System Administrator profile in a Managed Package ref this question

I am about the update all the tests to use System.RunAs with a user which has the Permission Set applied, but it doesn't feel right...

I am not sure what the best practice is here?

1
  • 2
    I had a similar issue with unlocked package version creation and runAs a User with a permission set was the only way I could fix it. Although it's a pain, it's worth it when you have strict FLS.
    – Naga
    Feb 9 at 1:29
5

Using System.RunAs in your test methods is the recommended way to solve these in Test class execution.

This ensures that the Test Execution context does not depend on the current user in the org. This has also been a practice in 1GP Managed package application before and is the right strategy to use the same approach for the Unlocked package and 2GP Managed packages.

However, With Spring 21, Salesforce provides a way you can add an unmanaged folder to your project directory that will be considered only for the test execution. This is ideal let's say you have a record type that you do not want to package or a profile on which your test depends.

This is documented here

You will need to create a separate directory to have them.

"packageDirectories": [
{
    "path": "force-app",
    "package": "TV_unl", 
    "versionName": "ver 0.1",
    "versionNumber": "0.1.0.NEXT",
    "default": true, 
    "unpackagedMetadata": {
        "path": "my-unpackaged-directory"
    }
}, 
 {
    "path": "my-unpackaged-directory",
    "default": false
 }
]

I would just use System.RunAs() if possible unless its something I have to have in the Unmanaged directory that I cannot create as a Test Data

1
  • Note that in this example the "my-unpackaged-directory" path is relative to the project root. Apr 24 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.