我正在用 kiwi 为网络 API 编写一些测试。
以下是相关代码:
///////////////////////////////////////// //// MyAPI.h //////////////////////////////////// ///////////
@protocol MyAPIDelegate<NSObject>
-(void) onMyMethodCall:(id)response;
-(void) onFail:(NSError*)error message:(NSString*)message;
@end
@interface MyAPI : NSObject
@property (nonatomic, weak) id<MyAPIDelegate> delegate;
-(void) myMethodCall;
@end
///////////////////////////////////////// //// MyAPI.m //////////////////////////////////// ///////////
@synthesize delegate
-(void) myMethodCall
{
NSDictionary *params = [Dictionary dictionaryWithObject:@"value1" forKey:@"param1"];
[self apiCallWithServerPath:@"logic/myMethodCall"
parameters:params
onSuccess:^(id response) {
[delegate onMyMethodCall];
}
onFailure:^(NSError *error, NSString* msg) {
[delegate onFail:error message:msg];
}];
}
-(void) apiCallWithServerPath:(NSString *)serverPath parameters:(NSDictionary *)parameters onSuccess:(void (^)(id))success onFailure:(void (^)(NSError *, NSString *))failure
{
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL urlWithString:@"http://www.myserver.com/"]];
[client setParameterEncoding:AFFormURLParameterEncoding];
[client postPath:serverPath
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
id response = [[JSONDecoder decoder] objectWithData:responseObject];
success(response);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"API call failed: error message = %@",[error localizedDescription]);
failure(error, [error localizedRecoverySuggestion]);
}];
}
///////////////////////////////////////// //// MyAPITest.m //////////////////////////////////// ///////////
SPEC_BEGIN(MyAPITest)
describe(@"MyAPITest should", ^{
__block MyAPI *api;
__block MyAPI *delegateMock;
beforeEach(^{
delegateMock = [KWMock mockForProtocol:@protocol(MyAPIDelegate)];
api = [[MyAPI alloc] init];
api.delegate = delegateMock;
});
afterEach(^{
delegateMock = nil;
api = nil;
});
it(@"should go to the server and get an answer, dont care about the value atm", ^{
[[api should] receive:@selector(myMethodCall)];
KWCaptureSpy *spy = [delegateMock captureArgument:@selector(onMyMethodCall:) atIndex:0];
// I usually put a breakpoint here...
[api myMethodCall];
[[expectFutureValue(spy.argument) shouldEventually] beNonNil];
});
});
SPEC_END
这是一个非常简单的测试,我正在逐步构建。最终我想测试 spy.argument 中的值,但现在我只对确保它不为零感兴趣。
运行测试总是失败:[FAILED] 请求的参数尚未被捕获。
调试不起作用:当我尝试在测试中放置断点(评论说)时,它永远不会进入方法。
同时,如果我将 NSLog(s) 放在 MyAPI 的 myMethodCall 中,它们不会打印在控制台上。
任何帮助将非常感激。
/////////////////////// 更新 ////////////////////////// ////////
事实证明,如果我评论/删除这一行(来自测试):
[[api should] receive:@selector(myMethodCall)];
测试有效。知道为什么这条线会导致问题吗?