I am using Alamofire in my iOS application for API calls. I am trying to stub this data out in the tests, I have tried Mockingjay and OHHTTPStubs but neither work, so I am now trying to stub the response that I receive back.
I need to create a Response with dummy data which I can pass to my other methods. Here is the initializer for the Response object in Alamofire:
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>)
However I cannot work out how create this object, as I cannot create a Result. Here is some of the result class from Alamofire:
public enum Result<Value, Error: ErrorType> {
case Success(Value)
case Failure(Error)
/// Returns `true` if the result is a success, `false` otherwise.
public var isSuccess: Bool {
switch self {
case .Success:
return true
case .Failure:
return false
}
}
/// Returns `true` if the result is a failure, `false` otherwise.
public var isFailure: Bool {
return !isSuccess
}
/// Returns the associated value if the result is a success, `nil` otherwise.
public var value: Value? {
switch self {
case .Success(let value):
return value
case .Failure:
return nil
}
}
/// Returns the associated error value if the result is a failure, `nil` otherwise.
public var error: Error? {
switch self {
case .Success:
return nil
case .Failure(let error):
return error
}
}
}
I can't seem to work out how to pass a result to the response object with a value in it, to represent an API response.
I think I'm getting confused about enums, and how they can have variables in them also.
Can anyone help me build a response?
Thanks.
ANSWERED
Thanks for the answer... Here is how you create the whole response with a json response
let london : NSDictionary = ["name" : "london", "latitude" : 23.00, "longitude" : 0.0, "id" : "london_gb"]
let paris : NSDictionary = ["name" : "paris", "latitude" : 30.00, "longitude" : -1.0, "id" : "paris_fr"]
let locations = NSArray(array: [london, paris])
let result = Result<AnyObject, NSError>.Success(locations)
var response = Response(request: NSURLRequest(), response: NSHTTPURLResponse(), data: NSData(), result: result)
see an example below:
let result = Result<String, NSError>.Success("Hello")
result.isSuccess // prints true
result.value // prints "Hello"
Hope that helps
Base one the answer of @66o but update to Swift 4 / Alamofire 4
import Alamofire
...
let result = Result<Any>.success("Hello")
let dataResponse = DataResponse(request: nil, response: nil, data: nil, result: result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With