[英]unit test case for a asynchronous method ios
i am new in the ios line. 我是ios行的新手。 I have a task to crete test case for this method.
我有一项任务要为此方法创建测试用例。
+ (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);
});
}
As through rnd i get to kno something related to XCTestExpectation
used to create unit test cases.... 通过rnd我知道用于创建单元测试用例的与
XCTestExpectation
相关的东西。
Just call fulfill
in the compeletion block. 只需在compeletion块中调用
fulfill
。 For example: 例如:
Assume the FunctionObj
holds the function 假设
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
Then the test case should be 然后测试用例应该是
- (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
}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.