为什么这个测试失败?
在
XCode 7
中创建一个新的 swift iOS 项目,名为带有 UI 测试的示例。
示例/ViewController.swift:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UIPasteboard.generalPasteboard().string = "test"
}
}
ExampleUITests/ExampleUITests.swift:
import XCTest
class ExampleUITests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
XCUIApplication().launch()
}
override func tearDown() {
super.tearDown()
}
func testExample() {
XCTAssertNotNil(UIPasteboard.generalPasteboard().string) //this fails
}
}
您无法从
UITest
访问任何类型的代码
UITest
是一个单独的进程,它使用可访问性来模拟模拟器/设备上的用户操作。因此,您只需检查 UI 并执行 UI 上可用的操作(点击按钮等)
我知道我参加聚会已经很晚了,但由于我刚刚偶然发现了同样的问题,我想将我的解决方案发布给其他想要测试
UIPasteboard
的人。
protocol UIPasteboardProtocol {
func setValue(_ value: Any, forPasteboardType pasteboardType: String)
func value(forPasteboardType pasteboardType: String) -> Any?
}
class ViewController: UIViewController {
private var pasteboard: UIPasteboardProtocol
// This init does not initiate a UIViewController and is created for demonstration purposes only
init(pasteboard: UIPasteboardProtocol = UIPasteboard.general) {
self.pasteboard = pasteboard
}
override func viewDidLoad() {
super.viewDidLoad()
pasteboard.setValue("test", forPasteboardType: "public.plain-text")
}
}
final class UIPasteboardMock: UIPasteboardProtocol {
public var valueForPasteboardType_Result: Any?
func setValue(_ value: Any, forPasteboardType pasteboardType: String) {
valueForPasteboardType_Result = value
}
func value(forPasteboardType pasteboardType: String) -> Any? {
valueForPasteboardType_Result
}
}
final class ViewControllerTests: XCTestCase {
private var sut: ViewController!
// Other code for your test class ...
func test_getValueFromPasteboard() {
// given
let pasteboard = UIPasteboardMock()
sut = ViewController(pasteboard: pasteboard)
// when
sut.viewDidLoad()
// then
XCTAssertNotNil(pasteboard.value(forPasteboardType: "public.plain-text"))
}
}