Salesforce - bypass running unnecessary unit tests during a deployment

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.

  1. Make a dev sandbox
  2. In production Salesforce deployment settings, select your new sandbox and ensure “Allow inbound changes” is enabled
  3. (in CLI) force login -i test.salesforce.com
  4. (in CLI) force export src
  5. Once the metadata export finishes, make the necessary code changes in /src/classes/
  6. Delete every directory in /src except for /classes
  7. 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
  8. (in CLI) force import -directory=src
  9. Sometimes the import fails for no reason, try it again
  10. Create an “Outbound change set” in the dev sandbox containing only the classes you changed, and upload to production
  11. In production Salesforce, find the changes in “Inbound change sets”, it should be in the “Change Sets Awaiting Deployment” section
  12. 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).
  13. Select “Run specified tests” and enter the names of test classes that test only what’s in the deployment, then click “Validate"
  14. Once they’ve passed, both the change set and the deployment should have a “Quick deploy” option.  Click that and you’re done!
If your changes don’t include any Apex code at all (e.g. you’re just importing a bunch of reports to update a field reference), you can do it all in the production org like a hero using the below. Note that it’s necessary to run just one single test, even if there’s no Apex changes that require testing.

force import -directory=src -r -l=RunSpecifiedTests -test=One_Test_That_Works