Skip to end of banner
Go to start of banner

Best Practices for Writing Tests

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Current »

Best practices

Naming your test

The name of your test should consist of three parts:

  • The name of the method being tested.

  • The scenario under which it's being tested.

  • The expected behavior when the scenario is invoked.

Why?

Naming standards are important because they explicitly express the intent of the test. Tests are more than just making sure your code works, they also provide documentation. Just by looking at the suite of unit tests, you should be able to infer the behavior of your code without even looking at the code itself. Additionally, when tests fail, you can see exactly which scenarios don't meet your expectations.

Arranging your tests

Arrange, Act, Assert is a common pattern when unit testing. As the name implies, it consists of three main actions:

  • Arrange your objects, create and set them up as necessary (setup).

  • Act on an object (set actions).

  • Assert that something is as expected (test actions).

The various sections (setup, test, tear down) are available for arranging in a TestCase:

Why?

  • Clearly separates what is being tested from the arrange and assert steps.

  • Less chance to intermix assertions with "Act" code.

Write minimally passing tests

The input to be used in a unit test should be the simplest possible in order to verify the behavior that you're currently testing.

Why?

  • Tests become more resilient to future changes in the codebase.

  • Closer to testing behavior over implementation.

Tests that include more information than required to pass the test have a higher chance of introducing errors into the test and can make the intent of the test less clear. When writing tests, you want to focus on the behavior.

Why unit tests?

-> Why Automated Testing?

  • No labels