2

単体テストケースを作成する必要があるアプリに次のメソッドがあります。
成功ブロックまたはエラーブロックが呼び出されたかどうかをテストする方法を誰でも提案できますか?

- (IBAction)loginButtonTapped:(id)sender
{
    void (^SuccessBlock)(id, NSDictionary*) = ^(id response, NSDictionary* headers) {
        [self someMethod];
    };

    void (^ErrorBlock)(id, NSDictionary*, id) = ^(NSError* error, NSDictionary* headers, id response) {
        // some code
    };

    [ServiceClass deleteWebService:@“http://someurl"
                              data:nil
                  withSuccessBlock:SuccessBlock
                    withErrorBlock:ErrorBlock];
}
4

1 に答える 1

1

比較的最近導入された API である期待を使用する必要があります。それらは、非同期メソッドのコールバックが呼び出されることを確認して、現在抱えている問題を正確に解決するために追加されました。

テストの結果に影響を与えるタイムアウトを設定することもできることに注意してください (たとえば、ネットワーク接続が遅いと誤検知が発生する可能性があります。もちろん、遅い接続をチェックしている場合を除きますが、それを行うにはもっと良い方法があります)。

- (void)testThatCallbackIsCalled {

    // Given
    XCTestExpectation *expectation = [self expectationWithDescription:@"Expecting Callback"];

    // When
    void (^SuccessBlock)(id, NSDictionary*) = ^(id response, NSDictionary* headers) {

        // Then
        [self someMethod];
        [expectation fulfill]; // This tells the test that your expectation was fulfilled i.e. the callback was called.
    };

    void (^ErrorBlock)(id, NSDictionary*, id) = ^(NSError* error, NSDictionary* headers, id response) {

     // some code

    };

    [ServiceClass deleteWebService:@“http://someurl"

                                           data:nil

                               withSuccessBlock:SuccessBlock

                                 withErrorBlock:ErrorBlock];
    };

    // Here we set the timeout, play around to find what works best for your case to avoid false positives.
    [self waitForExpectationsWithTimeout:2.0 handler:nil];

}
于 2015-08-03T11:56:50.713 に答える