简体   繁体   中英

iOS unit test: test that an KVO observer is called

I've got a KVO scenario test like this:

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

Currently I use a executed BOOL value to test if the observer block is called, is there any better way like an assert that must be called before test function end?

like this:

XCAssertCalledBeforeFunctionReturn()

So that I can change my code to:

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

You can use XCTestExpectation . There's a "manual" version where you tell it when it's been fulfilled, but for this case, you might be able to use the built-in XCTestCase.keyValueObservingExpectation(for:keyPath:handler:) method that's intended for precisely your scenario.

The major change from your desired sample code is, once you stand up the expectation, you need to tell it how long to wait before it concludes that the event is just never going to happen by blocking in waitForExpectations(timeout:handler:) after your setDate: call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM