The Unit in Unit Testing
The Unity Test Framework (UTF) enables Unity users to test their code in both Edit Mode and Play Mode, and also on target platforms such as Standalone, Android, iOS, etc.
Key Takeaways
Background
Developers often use test doubles as a way to facilitate this isolation. A test double is any object used in a test that takes the place of a collaborator. In his book xUnit Test Patterns, Gerard Meszaros defines several categories of test doubles: dummies, spies, stubs, fakes, and mocks. For our purposes, we’ll focus on the last two:
Isolation
Test isolation
Kent Beck, representing the classical approach to testing, argues that
“Unit tests are completely isolated from each other, creating their test fixtures from scratch each time.”
Recommended by LinkedIn
In this approach, the word unit in unit testing refers to the test itself: unit tests are isolated from other tests. Beck argues that “tests should be coupled to the behavior of code and decoupled from the structure of code.”
Tests written using this approach tend to have few mocks. They instead use instances of collaborating objects and even real supporting infrastructure (such as databases) to support each test run.
Subject isolation
Steve Freeman and Nat Pryce, representing the mockist approach to testing, argue that
“[unit tests] exercise objects, or small clusters of objects, in isolation.”
Freeman argues that unit tests are “important to help us design classes and give us confidence that they work, but they don’t say anything about whether they work together with the rest of the system.” In this approach, the word unit in unit testing refers to the subject being tested.
Tests written using this approach must use test doubles to stand in for collaborators and tend to have many mocks.
In practice
To determine the approach to use in practice, we must first enumerate the goals we are trying to achieve by writing tests. We want to:
With these goals in mind, I’d argue to start with the test isolation approach to unit tests. If each test runs reliably in isolation while using as many real collaborators as possible.
Conclusion
When determining your testing approach, think carefully about your approach to unit isolation, so you’re aware of the benefits and tradeoffs of starting with a classical or a mockist approach. Always be willing to adapt your approach depending on the nature of your collaborators. Ultimately we all want a fast, reliable test suite that gives us the confidence to ship, documents our intentions clearly, and helps us to design an extensible system.
Good try Amber Sharma. 👍