import SwiftUI
struct ContentView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 20) {
Text("\(count)")
.font(.largeTitle)
.accessibilityIdentifier("countLabel")
Button("Increment") {
count += 1
}
.accessibilityIdentifier("incrementButton")
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// XCUITest file
import XCTest
final class SimpleCounterUITests: XCTestCase {
var app: XCUIApplication!
override func setUpWithError() throws {
continueAfterFailure = false
app = XCUIApplication()
app.launch()
}
func testIncrementButtonIncreasesCount() throws {
let incrementButton = app.buttons["incrementButton"]
let countLabel = app.staticTexts["countLabel"]
XCTAssertEqual(countLabel.label, "0")
incrementButton.tap()
incrementButton.tap()
incrementButton.tap()
XCTAssertEqual(countLabel.label, "3")
}
}
The SwiftUI view uses a @State variable count to hold the number. The Text shows the current count and has an accessibility identifier countLabel so the UI test can find it. The Button labeled "Increment" increases the count by 1 when tapped and has an accessibility identifier incrementButton.
The XCUITest launches the app, finds the button and label by their accessibility identifiers, taps the button 3 times, and checks that the label updates to "3". This confirms the UI behaves as expected.