TE

Objective-C Testing

Objective-C testing conventions with XCTest and OCMock

Details

Language / Topic
objective-cObjective-C
Category
Testing

Rules

balanced
- Use `XCTest` as the primary test framework — place test files in a separate test target and name them `ClassNameTests.m`.
- Write test methods named `test<MethodUnderTest>_<Scenario>_<ExpectedBehavior>`: `- (void)testLogin_withInvalidCredentials_returnsAuthError`.
- Use `XCTAssertEqual`, `XCTAssertNil`, `XCTAssertTrue`, and `XCTAssertThrows` assertion macros — never use bare `NSAssert` in test code.
- Use `setUp` and `tearDown` methods to create and release test fixtures — call `[super setUp]` and `[super tearDown]` at the beginning and end respectively.
- Use `OCMock` for mocking: `id mockService = OCMClassMock([NetworkService class])` and stub with `OCMStub([mockService fetchData:...]).andReturn(...)`.
- Use `XCTestExpectation` for testing asynchronous code: create an expectation, fulfill it in the callback, and call `[self waitForExpectations:timeout:handler:]`.
- Test delegate callbacks by implementing the delegate protocol in the test class itself — simpler than mocking for single-use delegation.