Getting to an objects innards through categories

Normally you only want to test an object entirely through it’s public API. But for those times when you need to access an objects innards (but would or can’t expose them), you can make them public by defining the inner method as a category in your unit test.

- (void)testAddNumberToStack {
    Calculator *calc = [Calculator new];
    [calc pushOperand:1.0];
    XCTAssertEqual(1, calc.stackCount); // private
}

Calculator.m

-(NSUInteger)stackCount {
    return [self.myStack count]; // private
}

CalculatorTest.m

@interface Calculator (Tests) // category
-(NSUInteger)stackCount;
@end

Alternative to partical mocks

For those times when you want to override a method in a class under test, declare a new class and override the method in your test.

@interface TestSubclass : ClassUnderTest
@end

@implementation TestSubclass

- (void)methodToOverride
{
    ...
}

...
// In the test
- (void)testSubclass
{
    ClassUnderTest *testObject = [TestSubclass new];

    XCTAssert(...);
}

@end
Advertisements