TestCase:SwiftHTTP库未进行HTTP调用 [英] TestCase : SwiftHTTP library not making the HTTP call

查看:160
本文介绍了TestCase:SwiftHTTP库未进行HTTP调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重要事实

我忘了提到这个问题的一个重要因素.我在TestCase中运行它.我认为这个问题与TestCase有所关系,而不是等待异步completionHandler返回

I forgot to mention an important factor in the question. I am running this in a TestCase. I think this issue has something to do with the TestCase not awaiting for async completionHandler to return

Alamofire迁移到SwiftHTTP,因为我发现这要容易得多.

Migrated out from Alamofire to SwiftHTTP, since I found this much easier.

在SwiftHHTP上,无法知道生成了什么URL,返回了什么错误.例如,我尝试查看opt.debugDescription变量,它返回了一些类似描述字符串"<SwiftHTTP.HTTP: 0x60000007e540>"

On SwiftHHTP there is no way to know what URL got generated, what error it returned. For example, I tried to see the opt.debugDescription variable, it returned something cryptic like description String "<SwiftHTTP.HTTP: 0x60000007e540>"

我遵循的步骤

  • 我已将YES设置为Allow Arbitrary Loads.
  • 如果我粘贴fullurl ->http://120.0.0.1:8080/myapi/Driver/getDriver?driver=2243&domain=4345&key=asdfasdf,iPhone Simulator上的
  • Safari会以正确的JSON进行响应.甚至在我的Mac上运行的tomcat服务器上的catalina.out也会发出调试消息.
  • I have set YES to Allow Arbitrary Loads.
  • Safari on the iPhone Simulator responds with the correct JSON if I paste fullurl ->http://120.0.0.1:8080/myapi/Driver/getDriver?driver=2243&domain=4345&key=asdfasdf. Even catalina.out on the tomcat server running on my mac responds with a debug message.

但是,当我在Xcode的测试用例中运行此代码时,以下代码不会打印任何调试打印内容.

But when I run this in a test case under Xcode the below code prints none of debug print's.

  • -1->,-2->,-3->,什么都没打印.
  • 调试器断点也不会在这里停止.

代码

var getData = [String:String]()
       getData = ["domain": "4345",
           "driver" : "2343",
           "key" : "asdfasdf"]

       var urlComponents = URLComponents(string: fullURL)!
       var queryItems = [URLQueryItem]()
       queryItems = self.getData.map{ URLQueryItem(name : $0.0, value : $0.1) }
       urlComponents.queryItems = queryItems
       print("fullurl ->"+(urlComponents.url)!.absoluteString)

       do {
           let opt = try HTTP.GET((urlComponents.url)!.absoluteString)
                      opt.start { response in
               if let err = response.error {
                   print("--1-> error: \(err.localizedDescription)")
                   return //also notify app of failure as needed
               }
               print("--2--> opt finished: \(response.description)")
               self.responseData = response
           }
       } catch let error {
           print("--3--> got an error creating the request: \(error)")
       }    

编辑

即使将代码更改为httpshttp://www.google.com,也能获得相同的结果.

Even after changing the code to https or http://www.google.com, same result.

let testComponents = URLComponents(string: "https://www.google.com")!
        URLSession.shared.dataTask(with: (testComponents.url)!, completionHandler: {
            (data, response, error) in
            if(error != nil){
                print("..1>..")
            }else{
                do{
                    print ("..2>.." )
                    let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
                    self.responseData = json

                }catch let error as NSError{
                    print("..3>..")
                }
            }
        }).resume()

编辑1 此处 @Vivek的答案中进行了尝试.

EDIT 1 Tried from here @Vivek's answer.

callWebService(url: (urlComponents.url)!.absoluteString)
.
.
func callWebService(url : String) {
.
.
let callURL = URL.init(string: url)

什么也没打印,错误/JSON,什么也没有.

Nothing got printed again, Error / JSON, nothing.

推荐答案

是的,默认情况下,单元测试不会等待completionHandler被调用.如果在测试中调用异步函数,则无需更改函数代码,而只需更改测试的行为即可.

Yes, Unit Tests don't wait by default for the completionHandler to be called. If you call asynchronous functions in tests, you don't need to change the function's code, but the behavior of the test.

解决方案:XCTestExpectation

在测试类(XCTest的子类)中,添加以下属性:

In your test-class (the subclass of XCTest), add this property:

var expectation: XCTestExpectation?

用于异步请求的测试功能基本上看起来像这样:

A test-function for an asynchronous request could basically look like this:

func testRequest() {
    expectation = expectation(description: "Fetched sites") //1

    //2
    some.asyncStuffWithCompletionHandler() {
        someData in
        if someData == nil {
            XCTestFail("no data") //3
            return
        }

        //looks like the request was successful
        expectation?.fulfill() //4
    }

    //5
    waitForExpectations(timeout: 30, handler: nil)
}

说明

  1. 这定义了您希望测试后的代码执行的操作.但实际上,添加为描述并不重要.只是在运行测试时为您提供的信息

  1. This defines, what you expect the tested code to do. But actually, it's not important, what you add as description. It's just an information for you, when running the test

这是带有completionHandler的函数,您正在调用

This is the function with a completionHandler, you are calling

如果要让测试在completionHanlder中失败,请致电XCTestFail()

If you want to let the test fail within the completionHanlder, call XCTestFail()

如果completionHandler中的所有内容均按预期工作,请通过调用expectation?.fulfill来实现expectation.

If everything in the completionHandler worked as expected, fulfill the expectation by calling expectation?.fulfill.

这是重要的部分:这部分代码将在之前的 中执行!如果这将是功能的结束,则测试将停止.这就是为什么我们告诉测试等待直到达到期望(或经过一定时间)

Here comes the important part: This part of the code will be executed before the completionHandler! If this would be the end of the function, the test would be stopped. That's why we tell the test to wait until the expectations are fulfilled (or a certain amount of time passed)


关于单元测试的博客帖子. (请参阅"XCTestExpectation"部分).它是用旧的Swift语法编写的,但是概念是相同的.


There is an interesting blog post about Unit Tests. (see the section "XCTestExpectation") It's written in an old Swift syntax, but the concept is the same.

这篇关于TestCase:SwiftHTTP库未进行HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆