我在
Xcode 6(Beta 5)中使用XCTestExpectations进行异步测试.我所有的异步测试每次运行时都会单独通过.但是,当我尝试运行我的整个套件,一些测试不通过,应用程序崩溃.
我得到的错误是说API违规 – 多次调用 – [XCTestExpectation履行].事实上,这不是一个单一的方法;我的测试的一般格式如下所示:
- - (void) someTest {
- /* Declare Expectation */
- XCTestExpectation *expectation = [self expectationWithDescription:@"My Expectation"];
- [MyClass loginOnServerWithEmail:@"example@email.com" andPassword:@"asdfasdf" onSuccess:^void(User *user) {
- /* Make some assertions here about the object that was given. */
- /* Fulfill the expectation */
- [expectation fulfill];
- }];
- [self waitForExpectationsWithTimeout:5.0 handler:^(NSError *error) {
- /* Error handling here */
- }];
- }
再次,这些测试在单独运行时确实通过,并且它们实际上正在进行网络请求(按照预期的方式工作),但是一起,测试的集合无法运行.
另外,我正在运行OSX小牛,并使用Xcode 6(Beta 5).
解决方法
我不认为使用__weak或__block是一个很好的方法.我已经使用XCTestExpectation写了很多单元测试了一段时间,从来没有这个问题.我终于找到了可能在我的应用程序中导致错误的问题的真正原因.我的问题的根本原因是startAsynchronousTaskWithDuration多次调用completionHandler.在我修复之后,API违规行为已经消失了!
- [self startAsynchronousTaskWithDuration:4 completionHandler:^(id result,NSError *error) {
- XCTAssertNotNil(result);
- XCTAssertNil(error);
- [expectation fulfill];
- }];
虽然我花了几个小时来修复我的单元测试,但我来感谢API违规错误,这将有助于我避免在我的应用程序中的未来运行时问题.