Created
March 4, 2015 04:12
-
-
Save kazukitanaka0611/abffead24c0634305384 to your computer and use it in GitHub Desktop.
Swift 非同期テスト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestAPI: NSObject { | |
func call(url: NSURL, | |
success handleSuccess: ((NSDictionary) -> Void)?, | |
failure handleFailure: ((NSError) -> Void)?) { | |
let request = NSURLRequest(URL: url) | |
let session = NSURLSession.sharedSession() | |
let task = session.dataTaskWithRequest(request, | |
completionHandler: { data, response, connectionError in | |
if let error = connectionError { | |
handleFailure?(error) | |
return | |
} | |
var jsonError: NSError? | |
if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, | |
options: nil, | |
error: &jsonError) as? NSDictionary { | |
handleSuccess?(json) | |
return | |
} | |
if let error = jsonError { | |
handleFailure?(error) | |
return | |
} | |
let statusCode = (response as? NSHTTPURLResponse)?.statusCode | |
}) | |
task.resume() | |
} | |
} | |
test.json | |
{ | |
"firstName": "John", | |
"lastName": "Smith", | |
"_id": "123456" | |
} | |
import UIKit | |
import XCTest | |
class APISampleTests: XCTestCase { | |
func testHello() { | |
XCTAssertEqual("hello", "hello") | |
} | |
func testFailHello() { | |
XCTAssertNotEqual("hello", "hello!") | |
} | |
func testCallApi() { | |
let expectation: XCTestExpectation = self.expectationWithDescription("testCallApi") | |
let url = NSBundle(forClass: APISampleTests.self).URLForResource("test", withExtension: ".json") | |
let api = TestAPI() | |
api.call(url!, | |
success: { (json: NSDictionary) -> Void in | |
expectation.fulfill() | |
XCTAssertNotNil(json) | |
}, | |
failure: { (error: NSError) -> Void in | |
NSLog("NSError ====\(error.description)") | |
}) | |
self.waitForExpectationsWithTimeout(1, handler: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment