简体   繁体   English

iOS单元测试:测试是否调用KVO观察者

[英]iOS unit test: test that an KVO observer is called

I've got a KVO scenario test like this: 我有一个像这样的KVO场景测试:

- (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? 目前我使用一个执行的BOOL值来测试是否调用了观察者块,是否有更好的方法,如在测试函数结束之前必须调用的断言?

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 . 您可以使用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. 有一个“手动”版本,您可以在它完成时告诉它,但在这种情况下,您可以使用内置的XCTestCase.keyValueObservingExpectation(for:keyPath:handler:)方法,该方法适用于您的场景。

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. 从您想要的示例代码开始的主要变化是,一旦您满足期望,您需要告诉它等待多长时间之后才能通过在waitForExpectations(timeout:handler:)阻塞来阻止事件永远不会发生setDate: call。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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