IOS unit test: check the KVO watcher is called

I have a KVO script script like this:

- (void)testObserverCalled
{
    __block BOOL executed = NO;
    [[RACObserve(model, dateText) skip:1] subscribeNext:^(id x) {
        executed = YES;
    }];
    [model setDate:[NSDate date]];
    XCTAssertTrue(executed);
}

      

I am currently using the executed BOOL value to check if the observer block has been called, is there a better way like assert that should be called before the test function finishes?

like this:

XCAssertCalledBeforeFunctionReturn()

      

So, I can change my code to:

- (void)testObserverCalled
{
    [[RACObserve(model, dateText) skip:1] subscribeNext:^(id x) {
        XCAssertCalledBeforeFunctionReturn()
    }];
    [model setDate:[NSDate date]];
}

      

+3


source to share


1 answer


You can use XCTestExpectation

. There is a "manual" version where you tell when it will be executed, but for this case, you can use the built-in method XCTestCase.keyValueObservingExpectation(for:keyPath:handler:)

specifically for your scenario.



The main change to your desired code example is once you get into that wait, you need to say how long to wait before it concludes that the event simply won't happen, blocking waitForExpectations(timeout:handler:)

after your setDate:

call.

0


source







All Articles