Writing Test Case Methods

You add test cases to a test suite by adding test case methods to a test suite class. A test case method is an instance method of a test suite class that’s named test..., with no parameters, and whose return type is void. A test case method calls the code being tested (known as the unit), and reports whether the calls produced the expected result—for example, whether they return the anticipated value or raise an appropriate exception. Test case methods use a set of macros to check for the expected conditions and report their findings. “Unit-Test Result Macro Reference” describes these macros.

For a test case method to access the unit to be tested, you have to add the appropriate implementation files to the unit test target and import the corresponding header files into your test suite class. For an example of a project that uses unit tests, see the "iPhoneUnitTests" sample-code project.

This is the structure of a test case method:

- (void)test<test_case_name> {
   ...     // Set up, call test-case subject API.
   ST...   // Report pass/fail to testing framework.
   ...     // Tear down.

When Xcode runs unit tests, it invokes each test case method independently. Therefore, each method must prepare and clean up any auxiliary variables, structures, and objects it needs to interact with the subject API. Conveniently, you can add a pair of methods to a test suite class that are called before and after each test case method is invoked: setUp and tearDown. Just like test case methods, the type of both methods is void and they take no arguments.

This is an example of a setUp/tearDown method pair:

- (void)setUp {
   test_subject = [[[MyClass alloc] init] retain];
   STAssertNotNil(test_subject, @"Could not create test subject.");
- (void)tearDown {
   [test_subject release];