specta / expecta

A Matcher Framework for Objective-C/Cocoa
MIT License
1.59k stars 158 forks source link

Async test, why codes in callback block cannot be called? #154

Closed Banzuofan closed 9 years ago

Banzuofan commented 9 years ago

I am writing async test codes as the guide at https://github.com/specta/expecta, but i met a question, when run the test method, it seems that codes in callback block didn't run, i don't know what happen to my code, or something i missed. my code as follow:

- (void)testAsyncNetworkTask
{
    //XCTestExpectation *expecta = [self expectationWithDescription:@"asyncTask_login"];
    [Expecta setAsynchronousTestTimeout:15.0];

    __block id reponseData = nil;
    __block id error = nil;
    NSURLRequest *_request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    [NSURLConnection sendAsynchronousRequest:_request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        NSLog(@"%@", reponseData);
        reponseData = data;
        error = connectionError;

        //[expecta fulfill];
    }];

    XCTAssertNil(reponseData);
    expect(reponseData).willNot.beNil;
    expect(error).will.beNil;

//    [self waitForExpectationsWithTimeout:15 handler:^(NSError *error) {
//        //NSLog(@"%s, time out", __FUNCTION__);
//    }];
}

When I used XCTest to test my codes, it can run the codes in callback block, and i can see logs in console. I refered to AFNetworking demo containing expecta when i wrote my test codes. Hope you can understand what I said!

orta commented 9 years ago

Your test structure may work better this way using waitUntil

StatusReport commented 9 years ago

You're forgetting the parenthesis after the beNil (yes, it's troubling that the code compiles without them), so your spec probably terminates early before the callback is being called.

Try with:

expect(reponseData).willNot.beNil();
expect(error).will.beNil();
Banzuofan commented 9 years ago

Thanks for your replies, @StatusReport it works as your codes, i feel so shame for my carelessness