如何使用 OCMock 对带有响应块的 class 方法进行存根

How to stub a class method with response block using OCMock

HTTPResult *successResult = [[HTTPResult alloc] init];
successResult.success = YES;
successResult.content = @{@"key":@"value"};

id httpMock = OCMClassMock([HTTPUtility class]);

OCMStub(ClassMethod([httpMock requestWithHTTPMethod:HTTPRequestMethodGet                        
    URLString:@"testURL"
    parameters:[OCMArg any]
response:[OCMArg any]])).andDo(^(NSInvocation *invocation) {
            void(^response)(HTTPResult *) = nil;
            [invocation getArgument:&response atIndex:5];
            response(successResult);
        });

在 [OCMockObject dealloc] 方法中抛出 EXC_BAD_ACCESS 并在调用 class 方法时崩溃

使用特定块测试 class 方法的正确方法是什么

您似乎想捕获传递给 class 方法的响应参数块(不知道方法的签名我无法确定),所以不要使用 [OCMArg any] ,您可以使用块检查参数。参见第 4.3 节 here

[OCMArg checkWithBlock:^BOOL(id value) { /* return YES if value is ok */ }]

所以在你的例子中:

OCMStub(ClassMethod([httpMock requestWithHTTPMethod:HTTPRequestMethodGet                        
    URLString:@"testURL"
    parameters:[OCMArg any]
    response:[OCMArg checkWithBlock:^BOOL(HTTPResult *response) {
        response(successResult);
        return YES; // Replace this with a check for whether response is valid.
    }]);