How to test that staticTexts contains a string using XCTest

前端 未结 4 1757
走了就别回头了
走了就别回头了 2021-02-07 04:19

In Xcode UI testing, how do I test that staticTexts contains a string?

In the debugger, I can run something like this to print out all the content of staticTexts:

4条回答
  •  囚心锁ツ
    2021-02-07 04:39

    First, you need to set an accessibility identifier for the static text object you want to access. This will allow you to find it without searching for the string it is displaying.

    // Your app code
    label.accessibilityIdentifier = "myLabel"
    

    Then you can assert whether the string displayed is the string you want by writing a test by calling .label on the XCUIElement to get the contents of the displayed string:

    // Find the label
    let myLabel = app.staticTexts["myLabel"]
    // Check the string displayed on the label is correct
    XCTAssertEqual("Expected string", myLabel.label)
    

    To check it contains a certain string, use range(of:), which will return nil if the string you give is not found.

    XCTAssertNotNil(myLabel.label.range(of:"expected part"))
    

提交回复
热议问题