By applying the wrong way to reduce duplication, we’ve stumbled onto a mystery. Why are objects piling up before we run a single test? To solve this mystery, we’re going to dig into how XCTest creates and runs test cases.
It’s easy to assume that when XCTest runs a test case, three things happen:
Or, you may have assumed that XCTest creates one instance to run all the tests in a suite.
But both are incorrect. Here’s what really happens:
XCTest searches for all classes that inherit from XCTestCase.
For each such class, it finds every test method. These are methods whose names start with test, take no arguments, and have no return value.
For each such test method, it creates an instance of the class. Using Objective-C runtime magic, it remembers which test method that instance will run.
XCTest collects the instances of the subclass into a test suite.
When it’s finished creating all test cases, only then does XCTest begin running them.
What this means for our example is that XCTest finds MyClassTests. It searches for method names starting with “test,” and it finds two. So it creates two instances of MyClassTests: one instance to run test_methodOne, another to run test_methodTwo.
And it assembles these instances into a test suite before running any tests. Since each instance has a MyClass property, we’ve accidentally created two instances of MyClass.