下方是待測的 SwiftUI View
step1: 先使用 dummy text 當測項,並預期 test failed
func testMemoInputViewStart() throws {
let expect = "dummy"
/// MemoInputView 裡面裝載了 vStack, 而 Text 在 0 個位置
let string = try sut.inspect().vStack().text(0).string()
XCTAssertEqual(expect, string)
}
step2: 跑測試,會發現 failed
step3: 改測試,改成可以通過
func testMemoInputViewStart() throws {
let expect = "請輸入文字"
/// MemoInputView 裡面裝載了 vStack, 而 Text 在 0 個位置
let string = try sut.inspect().vStack().text(0).string()
XCTAssertEqual(expect, string)
}
step4: 跑測試,通過 tests
step1: 寫測試
func testMemoInputTextWithDummy() throws {
let dummyText = "foo"
let expect = "你輸入的是: foo"
try sut.inspect().vStack().textField(1).setInput(dummyText)
print("inputedText: \(sut.inputedText)")
let string = try sut.inspect().vStack().text(0).string()
XCTAssertEqual(string, expect)
}
step2: 跑測試
在 Xcode 的 console 區域,你會看到
Test Case '-[TwStockToolsTests.MemoInputViewTests testMemoInputTextWithDummy]' started.
2023-10-07 14:23:50.008738+0800 TwStockTools[72918:10598141] [SwiftUI] Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.
inputedText:
2023-10-07 14:23:50.011554+0800 TwStockTools[72918:10598141] [SwiftUI] Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.
/Users/cm0679/2swift/self/ITIronman_2023/TwStockTools/TwStockToolsTests/MemoInputViewTests.swift:42: error: -[TwStockToolsTests.MemoInputViewTests testMemoInputTextWithDummy] : XCTAssertEqual failed: ("請輸入文字") is not equal to ("你輸入的是: foo")
Test Case '-[TwStockToolsTests.MemoInputViewTests testMemoInputTextWithDummy]' failed (0.037 seconds)
console 區域的訊息有表明,在 View 裡面的 @State var inputedText: String 是不會變動的。
下一篇,我們來改寫 MemoInputView,讓這個 TextField 可以在測試時連動到 Binding 的值,並能讓 ViewInspector 能發動,並被測試。