Best Practices

Naming your tests

The name of your test should consist of three parts:

  • The name of the method being tested or the functionality being tested. Sometimes, we create failing test before the actual methods are created and we can use functionality name.
  • The scenario under which it's being tested.
  • The expected behavior when the scenario is invoked.

Arranging your tests

AAA Pattern: Arrange, Act, Assert is a common pattern when unit testing.

  • Arrange your objects, creating and setting them up as necessary.
  • Act on an object.
  • Assert that something is as expected.

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 are currently testing.

Avoid magic strings (hard coded)

Naming variables in unit tests is as important, if not more important, than naming variables in production code. Unit tests should not contain magic strings (hard coded strings).

Avoid logic in tests

When writing your unit tests avoid manual string concatenation and logical conditions such as if, while, for, switch, etc.

Prefer helper methods to setup and teardown

If you require a similar object or state for your tests, prefer a helper method than leveraging Setup and Teardown attributes if they exist.

Avoid multiple asserts

When writing your tests, try to only include one Assert per test. Common approaches to using only one assert include:

  • Create a separate test for each assert.
  • Use parameterized tests.

Validate private methods by unit testing public methods

Stub static references

When production code includes calls to static references it will be a problem because unit test will not have full control of the system under test.

To solve these problems, you'll need to introduce a seam into your production code. One approach is to wrap the code that you need to control in an interface and have the production code depend on that interface.