We had to urgently fix a bug in an Apex class written by a previous colleague, which was causing major issues with a customer-facing application on a Friday afternoon (because these things always happen then). We’d found the bug and updated the code easily enough, but Salesforce’s default deployment option of running all local unit tests was failing because of some completely unrelated tests that were failing.
Salesforce’s documentation (or at least the parts that I read) doesn’t clarify that you aren’t actually required to get 75% code coverage across all Apex code in your production org - you only need to get 75% coverage over the code you’re deploying. Here’s how to do it and get that emergency fix into production asap.
You’ll need the Force.com CLI for this, which you can easily install via chocolatey here. You can probably do the same with the Salesforce DX CLI, but I’m used to this other one.
- Make a dev sandbox
- In production Salesforce deployment settings, select your new sandbox and ensure “Allow inbound changes” is enabled
- (in CLI) force login -i test.salesforce.com
- (in CLI) force export src
- Once the metadata export finishes, make the necessary code changes in /src/classes/
- Delete every directory in /src except for /classes
- Modify /src/package.xml by removing all the <types> nodes except the one for “ApexClass”. This will make the import about a thousand times faster
- (in CLI) force import -directory=src
- Sometimes the import fails for no reason, try it again
- Create an “Outbound change set” in the dev sandbox containing only the classes you changed, and upload to production
- In production Salesforce, find the changes in “Inbound change sets”, it should be in the “Change Sets Awaiting Deployment” section
- Important: Don’t deploy the change set! Click “Validate” in the details page first. On the next page, the “Validate” button will be disabled for a while. Go make a cup of tea and wait for it to become enabled (refresh the page to check).
- Select “Run specified tests” and enter the names of test classes that test only what’s in the deployment, then click “Validate"
- Once they’ve passed, both the change set and the deployment should have a “Quick deploy” option. Click that and you’re done!