【问题标题】:GHUnit, OCMock: how to test if one of two specified block is called?GHUnit,OCMock:如何测试两个指定块之一是否被调用?
【发布时间】:2012-10-31 05:57:42
【问题描述】:

我有一个接受响应块和错误块的方法,我通过给它有效数据和无效数据来编写单元测试,因此它将分别调用响应块和错误块,但是使用 GHUnit 和 OCMock,我该如何测试如果调用了正确的块?

我在想:

对于有效数据: 回复 { GHAssertTrue(YES, @""); } 错误 { GHAssertTrue(NO, @"有效数据不应调用错误块"); }

无效数据反之亦然。

我做的对吗?

【问题讨论】:

    标签: objective-c ios unit-testing ocmock


    【解决方案1】:

    将断言放入块中的问题是,您不知道是否没有调用任何块。这就是我们所做的:

    __block BOOL done = NO;
    [classUnderTest doSomethingWithResultBlock:^(BOOL success) {
        done = YES;
    } errorBlock:^(BOOL success) {
        // should not be called
        expect(NO).to.beTruthy();
    }];
    while (!done) [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
    

    缺点是如果从不调用成功块,测试将在while循环中挂起。您可以通过添加超时来避免这种情况:

    NSDate *startTime = [NSDate date];
    __block BOOL done = NO;
    [classUnderTest doSomethingWithResultBlock:^(BOOL success) {
        done = YES;
    } errorBlock:^(BOOL success) {
        // should not be called
        expect(NO).to.beTruthy();
    }];
    while (!done && [startTime timeIntervalSinceNow] > -30) [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
    // make sure it didn't time out
    expect(done).to.beTruthy();
    

    【讨论】:

    • expecta 是我们在测试中使用的断言库。该语句相当于GHAssertTrue(done, @"Check for result block should not have timed out.");
    【解决方案2】:

    我会这样做:

    • 向测试类添加一个属性以指示调用了哪个块
    • 让每个块将该属性设置为不同的值
    • 调用
    • 检查属性值

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 2021-03-21
      • 2014-02-11
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      相关资源
      最近更新 更多