如何使用TDD测试类的属性?

时间:2012-12-20 15:49:26

标签: objective-c tdd respondstoselector

为什么当我在第43行使用方法respondsToSelector:instancesRespondToSelector:时,我无法绕过STAssertTrue?

//我的测试用例代码

- (void)testApiClass {
    //Check object
    NSString* classKey = @"Api";
    id obj = NSClassFromString(classKey);
    STAssertNotNil(obj, [NSString stringWithFormat:@"Model '%@' not found.", classKey]);
    //Check properties
    NSArray* properties =
    @[
        @"performSyncRequestWithUri::",
        @"performAsyncRequestWithUri:::",
    ];
    for (NSString* property in properties) {
        SEL propertySel = NSSelectorFromString(property);
        BOOL isRespondsToSel = [obj respondsToSelector:propertySel];
        STAssertTrue(isRespondsToSel, [NSString stringWithFormat:@"Property '%@' not found on object of class name '%@'", property, [obj class]]);
    }    
}


@interface Api : NSObject

- (NSDictionary*)performSyncRequestWithUri:(NSString *)requestUri params:(NSDictionary *)params;
- (void)performAsyncRequestWithUri:(NSString *)requestUri params:(NSDictionary *)params completionHandler:(void (^)(NSDictionary *, NSError *))completionBlock;

@end

2 个答案:

答案 0 :(得分:2)

properties数组中的字符串常量与Api接口中的选择器不匹配。

此外,这些选择器都不是指属性。一个属性有两个选择器:一个getter,如stringValue,没有冒号,和一个setter,如setStringValue:,它有一个冒号,(通常)以set开头。

不是将选择器嵌入字符串中,而是创建一个选择器数组:

SEL selectors[] = {
    @selector(performSyncRequestWithUri:params:),
    @selector(performAsyncRequestWithUri:params:completionHandler:),
    NULL
};

for (size_t i = 0; selectors[i]; ++i) {
    SEL selector = selectors[i];
    BOOL respondsToSelector = [obj respondsToSelector:selector];
    STAssertTrue(respondsToSelector, [NSString stringWithFormat:
        @"Object %@ doesn't respond to selector %s",
        obj, sel_getName(selector)]);
}

这里的优点是Xcode将为您自动完成选择器,您可以命令单击选择器以跳转到它们的定义。

答案 1 :(得分:1)

这些方法称为performAsyncRequestWithUri:params:completionHandler:performSyncRequestWithUri:params: