supermarin 建议如下方法:
@implementation KWSpec(Additions)
+ (void)myHelperMethod:(Car*)car {
[[car shouldNot] beNil];
};
@end
SPEC_BEGIN(FooBarSpec)
describe(@"A newly manufactured car", ^{
it(@"should not be nil", ^{
[self myHelperMethod:[CarFactory makeNewCar]];
});
});
SPEC_END
另一个选项是Doug suggests:
SPEC_BEGIN(FooBarSpec)
void (^myHelperMethod)(Car*) = ^(Car* car){
[[car shouldNot] beNil];
};
describe(@"A newly manufactured car", ^{
it(@"should not be nil", ^{
myHelperMethod([CarFactory makeNewCar]);
});
});
SPEC_END
它的好处是它非常适合异步场景:
SPEC_BEGIN(FooBarSpec)
__block BOOL updated = NO;
void (^myHelperAsync)() = ^()
{
[[expectFutureValue(theValue(updated)) shouldEventually] beYes];
};
describe(@"The updater", ^{
it(@"should eventually update", ^{
[[NSNotificationCenter defaultCenter] addObserverForName:"updated"
object:nil
queue:nil
usingBlock:^(NSNotification *notification)
{
updated = YES;
}];
[Updater startUpdating];
myHelperAsync();
});
});
SPEC_END
最后,如果您的辅助方法位于另一个类中,gantaa 建议一个聪明的 hack:
@interface MyHelperClass
+(void)externalHelperMethod:(id)testCase forCar:(Car*)car
{
void (^externalHelperMethodBlock)() = ^(){
id self = testCase; //needed for Kiwi expectations to work
[[car shouldNot] beNil];
};
externalHelperMethodBlock();
}
@end
SPEC_BEGIN(FooBarSpec)
describe(@"A newly manufactured car", ^{
it(@"should not be nil", ^{
[MyHelperClass externalHelperMethod:self forCar:[CarFactory makeNewCar]];
});
});
SPEC_END