Asynchronous unit test not being called by SenTest

2019-08-22 16:01发布

问题:

When I am running my unit test, I don't reach my breakpoint, and I think that the test isn't properly running my code.

I am trying to do an asynchronous test, which is part of my difficulty.

How do I set up the test so that testLookupBook will be called, as I hope that that will lead to everything else being called properly.

I am guessing that the function to test should be somewhere in the header file, but I did start my test method with test.

Here is my header file:

@interface jabBookScanTest : SenTestCase {
    jabBookScan *instance;
    NSArray *searchResult;
}
@end

And the implementation for the test is here:

- (void)MethodNameToCallBack:(jabBookScan *)manager 
            resultFromServer:(NSArray *)s {
    searchResult = s;
}

- (BOOL)waitForCompletion:(NSTimeInterval)timeoutSecs {
    NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutSecs];
    BOOL done = false;
    do {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
        if([timeoutDate timeIntervalSinceNow] < 0.0)
            break;
    } while (!done);

    return done;
}

- (void)testLookupBook {
   NSDate *fiveSecondsFromNow = [NSDate dateWithTimeIntervalSinceNow:5.0];
   [instance lookupBook:(NSString *)@"9780262140874"];
   [[NSRunLoop currentRunLoop] runUntilDate:fiveSecondsFromNow];
   STAssertTrue([self waitForCompletion:90.0], @"Failed to get any results in time");
}

回答1:

I would do like this

- (void)testLookupBook {
   NSDate *fiveSecondsFromNow = [NSDate dateWithTimeIntervalSinceNow:5.0];
   [instance lookupBook:(NSString *)@"9780262140874"];
   WAIT_WHILE(searchResult == nil, 1.0); 
}

The WAIT_WHILE(expressionIsTrue, seconds)-macro will evaluate the input until the expression is not true or the time limit is reached. Underneath it is using the NSRunLoop-pattern. You can find the project here:

https://github.com/hfossli/AGWaitForAsyncTestHelper



回答2:

I forgot to add the method to my header file.

@interface jabBookScanTest : SenTestCase<jabBookScanDelegate> {
    jabBookScan *instance;
    NSArray *searchResult;
}
- (void) testLookupBook;

@end