setUp() and tearDown() in XCTestCase
knowledge of XCTest lifecycle and test isolation.
setUp builds fresh state before each test, tearDown cleans up after, ensuring independence.
thinking they run once per class or sharing mutable state across tests.
WHAT THIS TESTS This probes whether you write isolated, repeatable tests and understand the XCTest execution lifecycle, a hallmark of disciplined testing.
A GOOD ANSWER COVERS setUp() is invoked before each individual test method in the case. Its job is to construct a fresh fixture, typically instantiating the system under test along with its mock or stub dependencies and assigning them to properties, so every test starts from an identical clean slate. tearDown() runs after each test method, undoing side effects, setting properties back to nil, deleting temporary files, or resetting any shared singletons the test touched. Because they run per method, no test can be polluted by another's residue, which keeps tests order-independent. Note the class-level variants setUp() class and tearDown() class run once for the whole suite.
COMMON WRONG ANSWERS Assuming they run only once per test class rather than once per test method. Putting shared mutable state in stored properties without resetting it, causing flaky, order-dependent tests. Doing expensive one-time setup in the per-test setUp when the class variant would be appropriate.
LIKELY FOLLOW-UPS What is the difference between the instance and class versions? When did async throwing setUp arrive and why is it useful? How do you handle resources that must be torn down even if a test throws? How does this map to the arrange step of arrange-act-assert?
ONE CONCRETE EXAMPLE Testing a CartViewModel, setUp() creates a fresh MockCheckoutService and a new CartViewModel bound to it, stored in properties. Each test then exercises the view model from a known empty cart. tearDown() sets both properties to nil so the next test cannot accidentally observe items added by the previous one, and so any retained references are released, preventing leaks from masking bugs.
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.