Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Testing Asynchronous Calls With FutureKit
import XCTest
import Nimble
import SwiftyJSON
import FutureKit
@testable import VillainApp
class VillainServiceTest: XCTestCase {
var service: VillainService!
var mockSession: MockSession!
let fakeHTTPResponse = HTTPURLResponse(url: URL(string: "http://www.wearevillains.com/")!,
statusCode: 200, httpVersion: nil, headerFields: nil)!
override func setUp() {
super.setUp()
self.continueAfterFailure = false
service = VillainService()
mockSession = MockSession()
service.session = mockSession
}
func testGetVillainList() {
let villainsDict = ["villainCount": 3,
"villains":[
["name": "Cruella DeVille",
"specialty": "unethical treatment of animals"],
["name": "Ursula",
"specialty": "fine print"],
["name": "Elphaba",
"specialty": "faking own death"],
]
]
let villainResponse = VillainResponse.init(fromJSON: JSON(villainsDict))
let villainData: Data = try! JSONSerialization.data(withJSONObject: villainsDict, options: .prettyPrinted)
let someResponse = URLResponse(url: URL(string: "http://www.wearevillains.com/")!, mimeType: nil, expectedContentLength: 0, textEncodingName: nil)
let future = self.service.getVillainList()
mockSession.completionHandler!(villainData, someResponse, nil)
future.onSuccess { (successResponse) -> Void in
expect(self.mockSession.request?.url?.scheme).to(equal("http"))
expect(self.mockSession.request?.url?.host).to(equal("www.wearevillains.com"))
expect(self.mockSession.request?.url?.path).to(equal("/team"))
expect(self.mockSession.request?.httpMethod).to(equal("GET"))
expect(successResponse).toEventually(equal(villainResponse))
expect(successResponse.login.expand.absoluteString).to(equal("http://www.wearevillains.com/"))
expect(self.mockSession.stubbedDataTask.resumeWasCalled).to(beTrue())
}
future.onCancel {
fail("Should have successfully obtained villains! Cancelled instead.")
}
future.onFail { (error) -> Void in
print(error)
fail("Should have successfully obtained villains! Failed instead.")
}
expect(future.isCompleted).to(beTrue())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment