如何在Obj C中编写异步方法的单元测试,而不需要完成块(completion block)?

6

我有一个调用API的方法,此方法内部没有任何完成处理程序。

-(void) methodToBeTested{
    [self callAPIWithCompletionHandler:^(NSArray *data,NSError *error)
     {
         //Here I get the response and sets the models.
     }];
}

现在我需要在API调用后,基于模型集合测试“methodToBeTested”方法。

有什么建议吗?


这实际上更像是一个集成测试。对于单元测试,通常会存根此方法并返回模拟数据,以便为其他测试组件做准备。 - bplattenburg
1个回答

3

例子:

XCTestExpectation *documentOpenExpectation = [self expectationWithDescription:@"document open"];

NSURL *URL = [[NSBundle bundleForClass:[self class]]
                              URLForResource:@"TestDocument" withExtension:@"mydoc"];
UIDocument *doc = [[UIDocument alloc] initWithFileURL:URL];

[doc openWithCompletionHandler:^(BOOL success) {
    XCTAssert(success);
    [documentOpenExpectation fulfill];
}];

[self waitForExpectationsWithTimeout:1 handler:^(NSError *error) {
    [doc closeWithCompletionHandler:nil];
}];

请查看Xcode测试文档下的异步操作写作测试。 https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html

1
问题中指出他无法使用完成块,但在答案中需要使用期望值,而期望值需要一个完成块。 - buttcmd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接