Run apex test on user story vs test coverage in deployment.If you add Apex code to a user story, you can then click on the Manage Apex Tests button. This will open the Apex Class Test page for that user story where you can calculate the Apex code coverage of the user story by clicking on Run Apex Tests. More information here.
The information below will help you understand the differences between running test from user stories, validations and deployments.
1. Run Apex Tests button in user stories.
The tests selected on the user story will run on the source environment of the user story. This is the environment where the user story is based at the moment of clicking on the button.
The coverage returned is based on the code of the classes in the source environment, not the feature branch. The code in the source environment for the classes on the user story should be the same as the code in the feature branch.
If the coverage for a class in a user story is not the same as the coverage you are seeing in the org, review this article.
2. Validate button in user stories.
The Validate button will create a promotion record and a validation deployment for the target environment. The test level for that validation deployment will be the one selected on the "Promotion Test Level" field on the user story that is being validated. The tests will run in the target environment during the validation deployment. The coverage returned is based on the code of the classes deployed to the target environment. Salesforce will first deploy (check only deployment) and then will run the test in the target environment.
When deploying a user story that contains classes, the test classes will run during the deployment in the target environment you are deploying to. The results are based on the code of the classes and test classes being deployed to the target environment and that code is taken from the promotion branch. You need to have that in mind if you are comparing the coverage returned when deploying with the coverage returned when running the classes directly in the org. Salesforce will first deploy and then will run the test in the target environment. If the code being deployed is different than the current code in the target environment, the coverage returned might be different.
Running apex test is a Salesforce feature. We cannot run tests on a feature branch or promotion branch directly. The tests must be run in actual Salesforce environments.