Unit tests
Principles of a good test
- simple and readable
- tests one component (class, function, etc - one unit) at a time
- independent
- repeatable (known fixed input produces the same known fixed output)
- test the results, not the implementation details
Structure
- setup: create needed objects and dependencies
- external dependencies (database, network requests, etc) should be mocked so that they don't affect the test results
- execute: run the unit of code being tested
- expect: verify that the result matches what is expected
Types of Mocks
- stub: returns the expected value with no other logic, ignores inputs
- mock: tests that it receives the expected inputs
- ex. a method on the mock is called 5 times, and/or with the correct arguments
- tied to implementation: if you change the code such that the method only needs to be called 1 time, the test will fail and need to be updated
- fake: a working implementation, but simplified from the production version
- ex. an in-memory database
- fakes can have their own suite of tests