UI 测试 UIPasteboard

问题描述 投票:0回答:2

为什么这个测试失败?

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
    }
}
ios swift ui-testing uipasteboard
2个回答
1
投票

您无法从

UITest

访问任何类型的代码

UITest
是一个单独的进程,它使用可访问性来模拟模拟器/设备上的用户操作。因此,您只需检查 UI 并执行 UI 上可用的操作(点击按钮等)


0
投票

我知道我参加聚会已经很晚了,但由于我刚刚偶然发现了同样的问题,我想将我的解决方案发布给其他想要测试

UIPasteboard
的人。

  1. 创建协议并添加您使用的所有必要方法
protocol UIPasteboardProtocol {
    func setValue(_ value: Any, forPasteboardType pasteboardType: String)
    func value(forPasteboardType pasteboardType: String) -> Any?
}    
  1. 使用粘贴板的属性。
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")
    }
}
  1. 创建模拟
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
   }
}
  1. 在测试中使用模拟
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"))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.