我正在尝试对我的应用程序中的网络代码进行单元测试,我有一些问题,我希望在我通过测试之前,我希望看到我的测试失败,以确保所有的测试都正常工作。问题是,它总是在流逝。我使用Xcode6-Beta7,以防这可能是问题所在
我使用Specta进行测试,并使用OHHTTPStubs将我的网络请求存根,并在响应中返回一个状态代码。
下面是我设置和拆卸的代码
beforeEach(^{
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return YES;
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
return [OHHTTPStubsResponse responseWithData:nil statusCode:200 headers:nil];
}].name = @"My Test Stub";
[OHHTTPStubs onStubActivation:^(NSURLRequest *request, id<OHHTTPStubsDescriptor> stub) {
NSLog(@"%@ stubbed by %@", request.URL, stub.name);
}];
});
afterAll(^{
[OHHTTPStubs removeAllStubs];
});在测试的下一部分(有问题的部分),我将创建我的类的一个实例,该实例操作一个NSMutableURLRequest,然后检查它是否为空。
context(@"Given that I create a http request with a URL", ^{
__block NLXApiBaseServices *baseService = [[NLXApiBaseServices alloc] init];
NSMutableURLRequest *testRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
it(@"should have a base service created", ^{
expect(baseService).toNot.beNil();
});第一个测试起作用,然后下一个测试使用存根。这应该会失败,因为我的存根应该返回200,并且我正在测试它是否等于400
it(@"should have a return code of 200", ^AsyncBlock{
[baseService dataWithHttpRequest:testRequest successCallback:^(NSInteger statusCode, NSDictionary *response, NSDictionary *responseHeaders) {
expect(statusCode).to.equal(400);
done();
} errorCallback:^(NSInteger statusCode, NSDictionary *response, NSError *error) {
}];
});这就是我使用AsyncBlock关键字执行异步测试,并使用done()表示测试完成的地方。我注意到的是,Xcode报告测试成功了,但是查看我控制台中的日志,我可以看到
Test Suite 'All tests' passed at 2014-09-07 22:11:22 +0000. Executed 95 tests, with 0 failures (0 unexpected) in 0.489 (0.816) seconds
在仔细检查我的日志后,我发现
2014-09-07 23:11:21.480 TwoUpTop[9255:116602] Request <http://www.google.com>
2014-09-07 23:11:21.486 TwoUpTop[9255:116661] http://www.google.com stubbed by My Test Stub
2014-09-07 23:11:21.487 TwoUpTop[9255:116648] NLXApiBaseServicesSpec.m:49 expected: 400, got: 200
Test Case '-[NLXApiBaseServicesSpec NLXApiBaseServices_Given_that_I_create_a_http_request_with_a_URL_should_have_a_return_code_of_200]' passed (0.012 seconds).所以现在,我很困惑-它抱怨状态码不相等-但测试正在通过!
有谁知道我是不是做错了什么?
如果有帮助,NLXApiBaseService类将从NSURLSessionConfiguration对象创建一个NSURLSessionDataTask,该对象是我使用defaultSessionConfiguration初始化NLXApiBaseService类时创建的。
发布于 2014-09-09 06:00:08
看起来这样做是有效的..
[baseService dataWithHttpRequest:testRequest successCallback:^(NSInteger statusCode, NSDictionary *response, NSDictionary *responseHeaders)
dispatch_async(dispatch_get_main_queue(), ^{
expect(statusCode).to.equal(200);
});
done();
} errorCallback:^(NSInteger statusCode, NSDictionary *response, NSError *error) {
}];当我测试expect(statusCode).to.equal(404);时,这也会正确地报告失败
这是在斯佩塔的Github页面上报道的:- https://github.com/specta/specta/issues/44
https://stackoverflow.com/questions/25715370
复制相似问题