Unit Testing HTTP traffic in Alamofire app

前端 未结 4 952
闹比i
闹比i 2020-12-12 20:57

I\'m struggling a bit to figure out how to best test an app that uses Alamofire to help sync with server data.

I want to be able to test my code that uses Alamofire

4条回答
  •  自闭症患者
    2020-12-12 21:37

    I'm adding another answer since I've just found this approach that in my opinion is easier and really simple to read and use.

    I've created a dummy Alamofire class that contains only the functions and the types necessary for tests. Now I include this file in the test target instead of the real Alamofire.

    For example I've created my version of the Request class where I define a couple of static variables that I valorise depending on the test, and for this class I've implemented only the init and the responseJSON function.

    public class Request {
    
        var request:String?
        struct response{
            static var data:NSHTTPURLResponse?
            static var json:AnyObject?
            static var error:NSError?
        }
    
        init (request:String){
            self.request = request
        }
    
        public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
    
            completionHandler(NSURLRequest(URL: NSURL(string:self.request!)!), Request.response.data, Request.response.json, Request.response.error)
            return self
        }
    }
    

    Now I can mock a response in a test:

    func testMytestFunction(){
        var HTMLResponse = NSHTTPURLResponse(URL: NSURL(string: "myurl")!, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
    
        Request.response.data = HTMLResponse
        Request.response.json = LoadDataFromJSONFile("MyJsonFile")
    
        request(.POST, "myurl", parameters: nil, encoding: ParameterEncoding.JSON).responseJSON {
            (request, response, JSON, error) -> Void in
            // the JSON and response variable now contains exactly the data that you have passed to Request.response.data and Request.response.json
        }
    }
    

    The request function is defined here:

    public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
    
        return Request(request: URLString.URLString)
    }
    
    public func request(URLRequest: URLRequestConvertible) -> Request {
    
        return Request(request: "fakecall")
    }
    

提交回复
热议问题