ios - IOS (Swift) 中的单元测试 BLE 应用程序

标签 ios swift unit-testing

我们开发了一个连接到 BLE 加密狗的应用程序,一切都通过 BLE 连接工作。

现在我们决定添加单元测试(是的,我知道采用 TDD 而不是这种方式要好得多,但情况就是这样)

在应用程序中,一切正常,但是当我尝试开发单元测试时,我无法通过连接阶段 (GAT),我没有让连接正常工作,无论如何测试都通过了一个一个接一个,不要停下来等待连接发生和身份验证什么都没有)

func testConnect() {
    if viewController == nil {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        viewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as? ViewController

        if let vc = viewController {
            _ = vc.view
        }
    }

    viewController?.connectBluetooth();
}


func testAuthenticateByPin() {
    delay(5) {
        var error: NSError? = nil

        self.datConnection?.connect("ABCDEFG", withError: &error)
        XCTAssertNotNil(error, "Connect Error: \(String(describing: error))")
        print("Connection: \(String(describing: error))")

        self.datConnection?.authenticate(byPIN: "AD$FGR#", withError: &error)
        XCTAssertNotNil(error, "Error: \(String(describing: error))")
        print("Auth: \(String(describing: error))")
    }
}



func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

有人知道如何创建 BLE 单元测试以及如何在单元测试之间创建延迟吗?

最佳答案

我在 Objective-C 中使用期望来进行网络操作测试。

您创建一个期望并在测试用例结束时等待它实现。当您收到连接通知或您必须等待的任何内容时,请调用 fulfill()。等待使用超时,如果通知永远不会到来(连接永远不会发生),测试将失败并出现未满足的期望。

来自 Apple 网站 ( here ) 的样本已经在 Swift 中:

func testDownloadWebData() {
    // Create an expectation for a background download task.
    let expectation = XCTestExpectation(description: "Download apple.com home page")
    // Create a URL for a web page to be downloaded.
    let url = URL(string: "https://apple.com")!
    // Create a background task to download the web page.
    let dataTask = URLSession.shared.dataTask(with: url) { (data, _, _) in
        // Make sure we downloaded some data.
        XCTAssertNotNil(data, "No data was downloaded.")
        // Fulfill the expectation to indicate that the background task has finished successfully.
        expectation.fulfill()
    }

    // Start the download task.
    dataTask.resume()
    // Wait until the expectation is fulfilled, with a timeout of 10 seconds.
    wait(for: [expectation], timeout: 10.0)
}

关于ios - IOS (Swift) 中的单元测试 BLE 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667575/

相关文章:

ios - 在真实设备上未授予访问照片库的权限

objective-c - 从 Objective-C 访问 Swift Delegate 的正确方法是什么?

iPhone 应用程序仅支持 Retina。 Apple 会接受该应用程序吗?

iphone - Xcode分析说“对象潜在泄漏”

ios - Swift:DismissViewController() 和关闭键盘的线程问题

java - Mockito 使用 Spring Boot 模拟 Java @Value

java - 在您事先不知道输出的情况下测试代码

ios - 默认今日小部件中的布局约束冲突

ios - 邮件撰写 View Controller 文本颜色不会改变

django - 在没有数据库的情况下使用 django-discover-runner