User Tools

Site Tools


test_doubles

Sources:

  1. Software Testing course at ITMO university by Kochubeev Nikolay Sergeevich

Test doubles

Test doubles are used in unit tests to mimic the real objects the tests depend on.

Test double types

There are several test doubles types:

  • dummy;
  • stub;
  • fake;
  • spy;
  • mock.

Dummy

Dummy is an object that's not actually used in the test. It is used as a placeholder, for example, when there needs a certain type of object to be passed as a parameter to initialize a method.

Stub

Stubs provide predetermined responses. They're used to isolate the behavior of the component from its dependencies. They're typically used to simulate the behavior of complex or external components (data bases, web services, external API).

Fake

A fake is a simplified real object. They're used for tests that require a real implementation but a lighter and faster one.

Spy

Spies record information about how they were interacted with during the test (how many times was the method called, what arguments were passed, the order of method calls).

Mock

Mocks are used to verify that certain interactions took place by being pre-programmed to expect certain specification of the calls.

Anti-patterns

FIXME

Over-mocking

If the mock expects way too specific calls, the test no longer checks for the behavior, but for the inner details of implementation.

Testing implementation instead of the behavior

When a test knows too much about the inner workings of the class (what methods are called and in what order). The slightest refactoring can break such a test.

Best practices

  1. Choose a correct test double.
  2. Give preference to fake where it's appropriate, as it's easier to maintain than mocks.
  3. Limit the amount of mocks. If a test requires more than 2-3 mocks, something went wrong.
  4. A test must fixate the business-result, not the inner details.
  5. Take out the creation of doubles into factories or test data builders. This improves readability.
  6. Use mocks/fakes for unit-tests, for integration – real services.
  7. Use clear names (SpyEmail, FakeRepo).
test_doubles.txt · Last modified: by plida