Replacing Code with Test Doubles Flashcards
What are test doubles?
A test double is a replacement for a component that looks and behaves similarly, and provides the same API, yet often is a simplified version thereof.
They can often have hard-coded behaviour configured during test setup.
Why use test doubles?
- Test doubles provide the isolation that unit tests require.
- Test doubles provide consistent and expected response every time.
- Test doubles are fast because they provide little to none executable code.
What are the variations of test doubles?
- Test stub
- Test spy
- Mock object
- Fake object
- Dummy object
What is a test stub?
A test double that simulates the behavior of a component by taking complete control over the responses and not responding to a request unless programmed to.
A test stub temporarily replaces a real component, so the original can be restored as needed.
A stub can be used to verify indirect input. For example, faking a database query response.
What is a test spy?
A test double that observes interactions with tested code. They are primarily used to count the number of times a component was called, along with how it was called and what it responded with.
Spies verify the indirect outputs of a component, and they can either be added to an existing component in order to see how it behaves, or replace it completely (like a stub).
What is a mock object?
A test double that is preprogrammed with expectations of how something is supposed to work and completely leave out the responses.
A mock verifies behavior. Specifically, the expectations around how something is called, including with what arguments and how many times.
A mock doesn’t return anything, which differentiated it from a stub. They are used to verify the use of the method that’s being tested.
What is a fake object?
A test double that is a working implementation of a component that takes a shortcut, typically for performance reasons. They are not usable in production and are intended only for testing purposes.
Example: replacing a database with an in-memory array.
What is a dummy object?
A test double that provides parameters for the function being tested.
Example: testing validation with arbitrary input.
In summary, what does a test stub do?
Verify indirect inputs.
In summary, what does a test spy do?
Verify indirect outputs for later verification.
In summary, what does a mock object do?
Verify indirect outputs against expectations.
In summary, what does a fake object do?
They are like mock objects in that they verify indirect outputs against expectations, but they run faster with less functionality.
In summary, what does a dummy object do?
Specify values used for testing.
What is Sinon?
It’s the most popular JavaScript library for test spies, stubs, and mocks. It can be used with any unit testing library.
What does Sinon create?
Spies, stubs, and mocks, as well as XMLHttpRequest for testing Ajax, and even setting up a fake server and more.