Welcome to part 3 of Test-Driven Development in Unity! In this video we’ll look at unit tests with multiple collaborators.
Part 1: Introduction
Part 2: Getting Started
Part 3: Social Unit Tests
Part 4: Heart Container Implementation
Part 5: Test Data Builders
Part 6: Safe Refactoring
Part 7: Basic Player Health
Part 8: An Event Driven UI
Unit Tests with Multiple Collaborators
The HeartContainer class will be responsible for multiple Hearts. It’s API will include methods to replenish and deplete that will have to manipulate a list of Hearts intelligently.
As a result, our tests will start to look more complicated and we’ll see how difficult it can be to write unit tests with multiple collaborators.
There are a couple of ways to handle unit tests with multiple collaborators. You can instantiate them in each test, store them in class properties, or retrieve them from builders.
Our unit tests will use a combination of the first two strategies, but this won’t scale well so eventually we’ll have to introduce builders.
- Researched ArgumentOutOfRangeException
- Drove the creation of the HeartContainer class by creating a failing test
- Discovered that we’ll need to expose more about a heart’s state in order to complete the HeartContainer’s implementation
Lessons & Takeaways
- There is no setup required in order to start unit testing in Unity. Unity’s test runner uses an implementation of NUnit. Unity will be able to run your tests as long as you use the attributes defined in NUnit’s documentation.
- Tightly coupling your code to Unity, or any library, can lead to problems down the road. Any dependencies should be abstracted away as soon as possible.
- Test-Driven Development allows you to build your source code organically. Upfront design is possible, and sometimes neccessary, but often times you can flesh out an entire algorithm purely through failing tests.
- Attempting to move duplication too soon can lead to unneeded code as a result of incorrect assumptions.