如何测试块是否被调用

发布于 2024-12-29 04:57:45 字数 552 浏览 3 评论 0原文

我有一个方法的单元测试,该方法应该调用完成块或失败块。现在我知道每种情况应该调用哪一个,因此我在不应调用的块中使用 STFail

我现在如何测试应该调用的块是否确实被调用?

这是我的设置:

NSString *parameter = @"foo";
[controller doSomethingWithParameter:parameter withcompletionBlock: 
^(NSString *result)
{
    // This block should be invoked
    // Check if the result is correct
    STAssertEquals(result, kSomeOKConstant, @"Result shout be 'kSomeOKConstant'");
} failedBlock:
^(NSString *errorMessage) {
    STFail(@"No error should happen with parameter '%@'",parameter);
}];

I have a unit test for a method that should call either a completion block or a failed block. Now I know for every case which one should be called so I use STFail in the block that should not be invoked.

How can I now test that the block that should be invoked is really invoked?

This is my setup:

NSString *parameter = @"foo";
[controller doSomethingWithParameter:parameter withcompletionBlock: 
^(NSString *result)
{
    // This block should be invoked
    // Check if the result is correct
    STAssertEquals(result, kSomeOKConstant, @"Result shout be 'kSomeOKConstant'");
} failedBlock:
^(NSString *errorMessage) {
    STFail(@"No error should happen with parameter '%@'",parameter);
}];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷迭香的记忆 2025-01-05 04:57:45

您需要添加块变量,并从块内部设置它们:

BOOL __block successBlockInvoked = NO;
BOOL __block failureBlockInvoked = NO;
NSString *parameter = @"foo";
[controller doSomethingWithParameter:parameter withcompletionBlock: 
^(NSString *result) {
     successBlockInvoked = YES;
     STAssertEquals(result, kSomeOKConstant, @"Result shout be 'kSomeOKConstant'");
} failedBlock:
^(NSString *errorMessage) {
    failureBlockInvoked = YES;
    STFail(@"No error should happen with parameter '%@'",parameter);
}];

此时,您可以对 successBlockInvokedfailureBlockInvoked 的值进行断言:如果预期的值不是设置,你的测试失败了。

You need to add block variables, and set them from inside your blocks:

BOOL __block successBlockInvoked = NO;
BOOL __block failureBlockInvoked = NO;
NSString *parameter = @"foo";
[controller doSomethingWithParameter:parameter withcompletionBlock: 
^(NSString *result) {
     successBlockInvoked = YES;
     STAssertEquals(result, kSomeOKConstant, @"Result shout be 'kSomeOKConstant'");
} failedBlock:
^(NSString *errorMessage) {
    failureBlockInvoked = YES;
    STFail(@"No error should happen with parameter '%@'",parameter);
}];

At this point you can make assertions about the values of successBlockInvoked and failureBlockInvoked: if the expected one is not set, your test has failed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文