I have Swift 2 code using Alamofire that queries a remote URL that it expects to return JSON. I've done enough interactive testing to be reasonably confident that it behaves correctly enough. Now I want to unit-test it so I can rely on this code and then move onto other things.
I'm new to Swift, although I've been programming OO Perl for decades, so there's probably something that I've missed.
Here's how I've set up the checking code so far (unimportant things such as how I get a username and password removed to avoid yak-shaving). The calling code specifies a username and password, and expects one of two callbacks to be called whenever a result is obtained. (I didn't get as far as dealing with errors, so please don't get side-tracked on that subject.)
struct checkUsernameHandler {
var onSuccess: () -> ()
var onFailure: () -> ()
}
struct checkUsernameOutput {
var authenticated: Bool?
}
func checkUsername(user: User, handler: checkUsernameHandler) {
Alamofire.request(.PUT, NSURL(string: baseURL + "/user/verify?key=" + apiKey)!,
parameters: [
"username": user.username!,
"password": user.password!,
],
encoding: .JSON
).responseJSON { response in
let checkusernameOutput = self.analyseCheckUsernameResponse(response)
if let authenticated = checkusernameOutput.authenticated {
if authenticated {
handler.onSuccess()
} else {
handler.onFailure()
}
}
}
}
func analyseCheckUsernameResponse (response: Response<AnyObject, NSError>) -> checkUsernameOutput {
var output = checkUsernameOutput()
if (response.result.isSuccess) {
if let JSON = response.result.value as? NSDictionary {
// ...
}
} else {
print("Didn't get proper JSON or something: \(response.result.error)")
}
return output
}
What I'm looking for is a way of taking raw JSON and passing it to Alamofire somehow, so I can generate a response object that has the appropriate things in it, including errors if it didn't get anything (timeout?) or the data returned was invalid (e.g. an HTML-format 404 or 500 page).
I'm happy enough at the moment with function checkUsername, so I'm not interested in anyone saying "use OHHTTPStubs". I'm looking at testing only the code that I'm uncertain about, which is the code I just wrote.
Aucun commentaire:
Enregistrer un commentaire