Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/100.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios XCode UI测试swizzle API类方法_Ios_Cocoa Touch_Xcode7_Xcode Ui Testing - Fatal编程技术网

Ios XCode UI测试swizzle API类方法

Ios XCode UI测试swizzle API类方法,ios,cocoa-touch,xcode7,xcode-ui-testing,Ios,Cocoa Touch,Xcode7,Xcode Ui Testing,我有一个带有两个按钮的简单应用程序,它调用JSON web服务并打印结果消息 我想尝试新的XCode 7 UI测试,但我不明白如何模拟API请求 为了简单起见,我构建了一个没有实际请求也没有任何异步操作的示例 我在主目标中有ZZSomeAPI.swift文件: import Foundation public class ZZSomeAPI: NSObject { public class func call(parameter:String) -> Bool { retu

我有一个带有两个按钮的简单应用程序,它调用JSON web服务并打印结果消息

我想尝试新的XCode 7 UI测试,但我不明白如何模拟API请求

为了简单起见,我构建了一个没有实际请求也没有任何异步操作的示例

我在主目标中有
ZZSomeAPI.swift
文件:

import Foundation
public class ZZSomeAPI: NSObject {
  public class func call(parameter:String) -> Bool {
      return true
  }
}
然后我的
ZZSomeClientViewController.swift

import UIKit
class ZZSomeClientViewController: UIViewController {
    @IBAction func buttonClick(sender: AnyObject) {
        print(ZZSomeAPI.call("A"))
    }
}
现在我添加了一个UITest目标,记录了点击按钮的过程,我得到了如下结果:

import XCTest
class ZZSomeClientUITests: XCTestCase {
    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        XCUIApplication().launch()
    }

    func testCall() {
        let app = XCUIApplication()
        app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Button).elementBoundByIndex(0).tap()
    }        
}
这样,运行测试将打印出
true
。但是我想在API返回
false
时包含一个测试,而不会弄乱API。因此,我在UI测试目标中添加了
ZZSomeAPI.swift
,并尝试了方法swizzling(UITest代码更新):

因此,
testSwizzle()
通过,这意味着swizzling有效。但是
testCall()
仍然打印
true
,而不是
false

是不是因为当UITest和main target是两个不同的应用程序时,swizzling只在测试目标上执行?
这有什么办法吗

我已经找到了,但我不确定如何在这里使用
launchArguments

在这个例子中只有一种情况,但我需要模拟
call()
方法,以获得不同测试方法的不同结果。。。如果我使用包含要返回的完整响应的
launchArgument
,例如
MOCK\u API\u RESPONSE
,则主目标应用程序委托将有一些“丑陋的仅测试”代码。。。有没有办法检查(在主目标中)它是否正在为UITest目标编译,以便它只包含该模拟启动参数的代码


最干净的选择确实是让swizzling开始工作…

Xcode UI测试在应用程序之外的单独应用程序中执行。因此,对测试运行程序应用程序中的类所做的更改不会影响测试应用程序中的类


这与单元测试不同,单元测试在应用程序进程中运行。

我接受了Mats的回答,因为实际问题(UI测试中的旋转)已经得到了回答

但我最终得到的当前解决方案是使用在线模拟服务器,因为swizzling的目标是模拟远程API调用

使用API URL的
public
属性更新了
ZZSomeAPI.swift
,而不是在方法中获取该属性:

import Foundation
public class ZZSomeAPI {
  public static var apiURL: String = NSBundle.mainBundle().infoDictionary?["API_URL"] as! String

  public class func call(parameter:String) -> Bool {
      ... use apiURL ...
  }
}
然后更新应用程序委托以使用
launchArguments

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        if NSProcessInfo().arguments.contains("MOCK_API") { // for UI Testing
            if let param = NSProcessInfo().environment["MOCK_API_URL"] {
                ZZSomeAPI.apiURL = param
            }
        }
        return true
    }
}
然后在我的UI测试用例类中创建
setupAPIMockWith
,以按需在mocky.io中创建模拟响应:

import XCTest
class ZZSomeClientUITests: XCTestCase {

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
    }

    func setupAPIMockWith(jsonBody: NSDictionary) -> String {
        let expectation = self.expectationWithDescription("mock request setup")
        let request = NSMutableURLRequest(URL: NSURL(string: "http://www.mocky.io/")!)
        request.HTTPMethod = "POST"

        var theJSONText: NSString?
        do {
            let theJSONData = try NSJSONSerialization.dataWithJSONObject(jsonBody, options: NSJSONWritingOptions.PrettyPrinted)
            theJSONText = NSString(data: theJSONData, encoding: NSUTF8StringEncoding)
        } catch {
            XCTFail("failed to serialize json body for mock setup")
        }

        let params = [
            "statuscode": "200",
            "location": "",
            "contenttype": "application/json",
            "charset": "UTF-8",
            "body": theJSONText!
        ]
        let body = params.map({
            let key = $0.0.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
            let value = $0.1.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
            return "\(key!)=\(value!)"
        }).joinWithSeparator("&")
        request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")

        var url: String?

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            XCTAssertNil(error)

            do {
                let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
                XCTAssertNotNil(json["url"])
                url = json["url"] as? String
            } catch {
                XCTFail("failed to parse mock setup json")
            }

            expectation.fulfill()
        }

        task.resume()

        self.waitForExpectationsWithTimeout(5, handler: nil)
        XCTAssertNotEqual(url, "")

        return url!
    }

    func testCall() {
        let app = XCUIApplication()
        app.launchArguments.append("MOCK_API")
        app.launchEnvironment = [
            "MOCK_API_URL": self.setupAPIMockWith([
                    "msg": [
                        "code": -99,
                        "text": "yoyo"
                    ]
                ])
        ]
        app.launch()

        app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Button).elementBoundByIndex(0).tap()
        app.staticTexts["yoyo"].tap()
    }

}

关于如何干净地使用launchArguments而不影响公共版本中的代码,有什么提示吗?类似于objC#IFDEF TESTENV if launchArgument的东西#Endi感谢您的确认,也许我会回到单元测试而不是UI,尽管能够在不调用远程API(我不控制)的情况下测试UI会很好
import XCTest
class ZZSomeClientUITests: XCTestCase {

    override func setUp() {
        super.setUp()
        continueAfterFailure = false
    }

    func setupAPIMockWith(jsonBody: NSDictionary) -> String {
        let expectation = self.expectationWithDescription("mock request setup")
        let request = NSMutableURLRequest(URL: NSURL(string: "http://www.mocky.io/")!)
        request.HTTPMethod = "POST"

        var theJSONText: NSString?
        do {
            let theJSONData = try NSJSONSerialization.dataWithJSONObject(jsonBody, options: NSJSONWritingOptions.PrettyPrinted)
            theJSONText = NSString(data: theJSONData, encoding: NSUTF8StringEncoding)
        } catch {
            XCTFail("failed to serialize json body for mock setup")
        }

        let params = [
            "statuscode": "200",
            "location": "",
            "contenttype": "application/json",
            "charset": "UTF-8",
            "body": theJSONText!
        ]
        let body = params.map({
            let key = $0.0.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
            let value = $0.1.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
            return "\(key!)=\(value!)"
        }).joinWithSeparator("&")
        request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
        request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")

        var url: String?

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in

            XCTAssertNil(error)

            do {
                let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSDictionary
                XCTAssertNotNil(json["url"])
                url = json["url"] as? String
            } catch {
                XCTFail("failed to parse mock setup json")
            }

            expectation.fulfill()
        }

        task.resume()

        self.waitForExpectationsWithTimeout(5, handler: nil)
        XCTAssertNotEqual(url, "")

        return url!
    }

    func testCall() {
        let app = XCUIApplication()
        app.launchArguments.append("MOCK_API")
        app.launchEnvironment = [
            "MOCK_API_URL": self.setupAPIMockWith([
                    "msg": [
                        "code": -99,
                        "text": "yoyo"
                    ]
                ])
        ]
        app.launch()

        app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Button).elementBoundByIndex(0).tap()
        app.staticTexts["yoyo"].tap()
    }

}