我是ios系列的新手。我有一个任务来克服这种方法的测试用例。
+ (void)myMethod:(NSString *)paramA callback:(void(^)(NSString *result, BOOL success))callback;
// ... Some code that runs async (for example, something that fetches data from the internet)...
// Call the callback function in a background thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
callback(@"Success", YES);
});
}
通过rnd我知道用于创建单元测试用例的XCTestExpectation
相关的东西......
答案 0 :(得分:0)
只需在竞争栏中调用fulfill
即可。例如:
假设FunctionObj
持有函数
@interface FunctionObj : NSObject
+ (void)myMethod:(NSString *)paramA callback:(void(^)(NSString *result, BOOL success))callback;
@end
@implementation FunctionObj
+ (void)myMethod:(NSString *)paramA callback:(void(^)(NSString *result, BOOL success))callback {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
callback(@"Success", YES);
});
}
@end
那么测试用例应该是
- (void)testAsyncFunction {
XCTestExpectation * expectation = [self expectationWithDescription:@"Test async method"];
[FunctionObj myMethod:@"1" callback:^(NSString *result, BOOL success) {
XCTAssert(success,"should be succeed");
XCTAssertNotNil(result,@"Should not be nil");
[expectation fulfill];
}];
[self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
//Do something when time out
}];
}