Search code examples
xcodetddocunitxctest

How can I check a property exists on an object using OCUnit/XCTest?


I'm trying to further my experience with TDD, and I'd like to know how I can check if a property exists on a class. Specifically, I want to ensure the object has a double named accumulator.

//
//  CSCalculatorModel.h
//  Calculator
//

#import <Foundation/Foundation.h>

@interface CSCalculatorModel : NSObject

@property (nonatomic) double accumulator;

@end

I know I can use tests like the following for objects, but how do I test C scalars?

- (void)testExample
{
    XCTAssertNotNil(calculatorClass.accumulator, @"Accumulator property does not exist on calculator class");
}

Solution

  • To verify the property's existence, call +instancesRespondToSelector on your class to make sure the property's generated getter method exists:

    - (void)testExample {
        XCTAssertTrue([CSCalculatorModel instancesRespondToSelector:@selector(accumulator)], @"Accumulator property does not exist on calculator class");
    }
    

    Peter Hosey's answer to a similar question might be helpful for figuring out how to test the property's type.