title: How do I mock an Alamofire response only?
body: <p>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.</p>
  
  <p>I'm new to Swift, although I've been programming OO Perl for decades, so there's probably something that I've missed.</p>
  
  <p>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.)</p>
  
  <pre><code>struct checkUsernameHandler {
      var onSuccess: () -&gt; ()
      var onFailure: () -&gt; ()
  }
  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&lt;AnyObject, NSError&gt;) -&gt; 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
  }
  </code></pre>
  
  <p>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).</p>
  
  <p>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.</p>
  
  <p><strong>EDIT</strong>: Having faffed about some more, it looks like Alamofire's internals are sufficiently connected that to create a fake Response, I need to do pretty much all of the work involved in setting up a network connection <em>anyway</em>. So perhaps the answer is "it's too much hassle to do that"?</p>