UI Test in SwiftUI – Part-1

Step_01: Select your Xcode and in iOS target give project name like “UITestAppDemo” and also turn on the inlcude Test checkbox.

Step_02: Replace ContentView.Swift file code by below code:

struct ContentView: View {
    
    @State private var showLoginView: Bool = false
    
    var body: some View {
        VStack {
            Text("Good Morning!")
                .font(.title)
            Spacer().frame(height: 25)
            Button {
                showLoginView = true
            } label: {
                Text("Login")
            }

        }
    }
}

Step_03: After creating project you will see there are two folder created one is UITestAppDemoTests and another is UITestAppDemoUITests. We will enter the second one. Here we will see some code automatically generate which will help for us writing UI test code. All test class inherits from XCTestCase.

setUpWithError(): This is the place where initialize all properties and it’s called before any test executing.
tearDownWithError(): It’s called after complete running test & also released any resources or instance created previous method.
textExample(): Any test method written by befor test keyword.
testLaunchPerformance(): It’s give test performance value.

Step_04: Now we will write our first test case. We will check “Good Morning” text exist or nor like below: Befor write code we will set let app = XCUIApplication() object in globally and also launch the test method from setUpWithError() method after continueWithFailure = false line:

    func testGoodMorningLabel() throws {
        // UI tests must launch the application that they test.
        let morning = app.staticTexts["Good Morning"]
        XCTAssert(morning.exists)
    }

11 thoughts on “UI Test in SwiftUI – Part-1

Leave a Reply

Your email address will not be published. Required fields are marked *