Make sure you can reproduce the bug on your test site. (If the steps to reproduce the issue are unclear, you can document them or add a comment asking for clarification. If you cannot figure out how to reproduce the bug, choose a different issue.)

Your task now is to create an automated test that follows the steps to reproduce the issue and asserts the expected result. The test should fail when the bug is present and pass once the bug is fixed.

Determine which file should contain the automated test.

If the bug is related to a specific core module, the test should be added to:

If the bug is related to a core subsystem (such as the menu system), look for an appropriate file in the appropriate directory.

for Drupal 7.x: modules/simpletest/tests/

for Drupal 8.x: core/modules/system/src/Tests/

Look at the different test case classes in that file and determine if one is a good fit for your test.

In Drupal 7, the test should extend DrupalWebTestCase. In Drupal 8, the test should extend Drupal\simpletest\WebTestBase. (Note that many modules have a base helper test class; if so, the test should probably extend that class instead.)

Consider the class's name, description, and setUp() method. If there is no class that is a good fit, add a new class for your test at the end of the file. (For more information, see the SimpleTest documentation.)

Add a test method to the class for your automated test. (In some cases, you may be able to extend an existing test method.)

In Drupal 7:

Use DrupalWebTestCase methods like drupalGet() and drupalPost() to programmatically execute the steps to reproduce the bug.

If there is already a patch to fix the bug, apply that patch to your test site along with your automated test, clear the cache, and run the test again. The test should now pass. Create a second patch that contains your test code together with the fix.

Create a new comment on the issue and upload your patch as an attachment. If you also created a patch containing a fix for the bug, upload the test-only patch as the first attachment and the combined test & fix patch as the second. If you are updating a previously uploaded patch, you should also upload an interdiff from the last patch to your new patch. Set the issue status to "Needs Review" so that the patches are automatically tested by the Drupal.org testbots. This makes it much easier for reviewers to see the problem exposed by the test-only patch, the proposed changes to fix the problem, and any new material added since the last patch. For a good example, see https://www.drupal.org/node/2277753#comment-9014925.