gpt4 book ai didi

swift - 从辅助方法调用的 XCTestCase 扩展如何知道主测试用例设置了哪些属性?

转载 作者:行者123 更新时间:2023-11-30 12:58:06 28 4
gpt4 key购买 nike

背景

以下测试调用 XCTestCase 扩展的方法。目标:

  • waitForElementExists 方法因元素存在而返回,或者
  • waitForElementExists 方法调用它的测试用例/setUp 方法失败,因为该元素在指定时间内不存在

UI Automation XCTestCase 扩展等待方法:

extension XCTestCase
{
/**
Wait for the view to load
Note: Must be a part of XCTestCase in order to utilize expectationForPredicate and waitForExpectationsWithTimeout

- Parameter
- element: The XCUIElement representing the view
- timeout: The NSTimeInterval for how long you want to wait for the view to be loaded
- file: The file where this method was called
- line: The line where this method was called
*/
func waitForElementExists(element: XCUIElement, timeout: NSTimeInterval = 60,
file: String = #file, line: UInt = #line)
{
let exists = NSPredicate(format: "exists == true")

expectationForPredicate(exists, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(timeout) { (error) -> Void in
if (error != nil)
{
let message = "Failed to find \(element) after \(timeout) seconds."
self.recordFailureWithDescription(message,
inFile: file, atLine: line, expected: true)
}
}
}
}

waitForExpectationsWithTimeout 正常工作的示例

测试用例

override func setUp()
{
super.setUp()

// Stop immediately when a failure occurs.
continueAfterFailure = false

XCUIApplication().launch()

waitForElementExists(XCUIApplication().buttons["Foo"])
}

func testSample()
{
print("Success")
}

这有效! testSample 从未被调用。

But what if we move the waitForElementExists call to a helper method?

waitForExpectationsWithTimeout 成功返回但不应该返回的示例

在这里,测试用例继续进行,就好像断言从未发生过一样。如果我在 waitForElementExists 中放置一个断点,我会看到 continueAfterFailure 设置为 true,因此很明显它没有连接到与主测试用例相同的代码。

测试用例

lazy var SomeHelper = SomeHelperClass()

override func setUp()
{
super.setUp()

// Stop immediately when a failure occurs.
continueAfterFailure = false

XCUIApplication().launch()

SomeHelper.waitForReady()

}

func testSample()
{
print("Success")
}

帮助文件

class SomeHelperClass: XCTestCase
{
/**
Wait for the button to be loaded
*/
func waitForReady()
{
waitForElementExists(XCUIApplication().buttons["Foo"])
}
}

最佳答案

由于您的帮助程序类是 XCTestCase 的子类,因此它有自己的 continueAfterFailure 属性,默认情况下为 true。

如果您想要一个辅助类,它不应该从 XCTestCase 派生,因为 XCTestCase 子类应该实现测试方法。如果您需要从帮助程序类中的 XCTestCase 扩展访问功能,请在创建帮助程序类时按组合传递测试用例对象。

class SomeHelper {

let testCase: XCTestCase

init(for testCase: XCTestCase) {
self.testCase = testCase
}

func await(_ element: XCUIElement) {
testCase.waitForElementExists(element)
}

}

class MyTests: XCTestCase {

let app = XCUIApplication()
var helper: SomeHelper!

func setUp() {
continueAfterFailure = false
helper = SomeHelper(for: self)
helper.await(app.buttons["foo"])
}

}

关于swift - 从辅助方法调用的 XCTestCase 扩展如何知道主测试用例设置了哪些属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40184109/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com