在我的 XCUITest 中解析 JSON 文件时出现问题

发布于 2025-01-11 10:54:39 字数 3660 浏览 2 评论 0原文

JSON 文件:“凭据”

[
    
{
        
"name" : Tom Harry
        
"email" : [email protected]
        
"password" : tomharry123
    
},
    
    {
        "name" : Sam Billings
        "email" : [email protected]
        "password" : sambillings789
    }
]

实用程序文件:

import Foundation
import XCTest

class Utils {
    
    static func loadData(filename : String) -> [Any] {
        let filePath = Bundle(for: self).path(forResource: filename, ofType: "json") ?? "default"
        let url = URL(fileURLWithPath: filePath)
        do {
            let data = try Data(contentsOf: url)
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            let array =  json as! [Any]
            if array.isEmpty {
                XCTFail("Source file \(filename) is empty.")
            }
            return array
            }
            catch {
                    XCTFail("File \(filename) not found.")
                    return []
                }
    }
}

TestFile:

import XCTest

class UITests: XCTestCase {
    var app : XCUIApplication!

    override func setUpWithError() throws {
        launchApp()
        continueAfterFailure = false
    }

    func launchApp() {
        app = XCUIApplication()
        app.launch()
        print("APPLICATION IS LAUNCHED")
    }
    
    func signUp(fullName : String, email : String, password : String) {
        let fullNameTextField = app.textFields.matching(identifier: "full name").element
        let emailTextField = app.textFields.matching(identifier: "email").element
        let passwordTextField = app.textFields.matching(identifier: "password").element
        if fullNameTextField.exists {
            fullNameTextField.tap()
            fullNameTextField.typeText(fullName)
        }
        if emailTextField.exists {
            emailTextField.tap()
            emailTextField.typeText(email)
        }
        
        if passwordTextField.exists {
            passwordTextField.tap()
            passwordTextField.typeText(password)
        }
        
        
        
    }
  
    func register() {
        let registerButton = app.buttons.matching(identifier: "register").element
        XCTAssert(registerButton.waitForExistence(timeout: 5), "REGISTER BUTTON IS NOT PRESENT")
        if registerButton.exists {
            print("REGISTER BUTTON IS PRESENT")
            registerButton.tap()
            print("REGISTER BUTTON IS TAPPED")
        }
    }
    
    func testSignUp(){
        let dataSource = Utils.loadData(filename: "credentials")
        for iteration in dataSource {
            guard let user = iteration as? [String : Any] else {return}
            let fullname = user["name"] as! String
            let email = user["email"] as! String
            let password = user["password"] as! String
            signUp(fullName: fullname, email: email, password: password)
        }
    
    }
    
    func testflowtest() {
        register()
        testSignUp()
    }
        
}

在测试文件中运行 testFlowTest 函数后,显示“未找到凭据文件” 错误。

我想用 JSON 文件中的姓名、电子邮件、密码填写注册文本字段。

这是使用后显示错误的图像 XCTFail("错误:\(错误)")

在此处输入图像描述

JSON file : "credentials"

[
    
{
        
"name" : Tom Harry
        
"email" : [email protected]
        
"password" : tomharry123
    
},
    
    {
        "name" : Sam Billings
        "email" : [email protected]
        "password" : sambillings789
    }
]

Utility file :

import Foundation
import XCTest

class Utils {
    
    static func loadData(filename : String) -> [Any] {
        let filePath = Bundle(for: self).path(forResource: filename, ofType: "json") ?? "default"
        let url = URL(fileURLWithPath: filePath)
        do {
            let data = try Data(contentsOf: url)
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            let array =  json as! [Any]
            if array.isEmpty {
                XCTFail("Source file \(filename) is empty.")
            }
            return array
            }
            catch {
                    XCTFail("File \(filename) not found.")
                    return []
                }
    }
}

TestFile:

import XCTest

class UITests: XCTestCase {
    var app : XCUIApplication!

    override func setUpWithError() throws {
        launchApp()
        continueAfterFailure = false
    }

    func launchApp() {
        app = XCUIApplication()
        app.launch()
        print("APPLICATION IS LAUNCHED")
    }
    
    func signUp(fullName : String, email : String, password : String) {
        let fullNameTextField = app.textFields.matching(identifier: "full name").element
        let emailTextField = app.textFields.matching(identifier: "email").element
        let passwordTextField = app.textFields.matching(identifier: "password").element
        if fullNameTextField.exists {
            fullNameTextField.tap()
            fullNameTextField.typeText(fullName)
        }
        if emailTextField.exists {
            emailTextField.tap()
            emailTextField.typeText(email)
        }
        
        if passwordTextField.exists {
            passwordTextField.tap()
            passwordTextField.typeText(password)
        }
        
        
        
    }
  
    func register() {
        let registerButton = app.buttons.matching(identifier: "register").element
        XCTAssert(registerButton.waitForExistence(timeout: 5), "REGISTER BUTTON IS NOT PRESENT")
        if registerButton.exists {
            print("REGISTER BUTTON IS PRESENT")
            registerButton.tap()
            print("REGISTER BUTTON IS TAPPED")
        }
    }
    
    func testSignUp(){
        let dataSource = Utils.loadData(filename: "credentials")
        for iteration in dataSource {
            guard let user = iteration as? [String : Any] else {return}
            let fullname = user["name"] as! String
            let email = user["email"] as! String
            let password = user["password"] as! String
            signUp(fullName: fullname, email: email, password: password)
        }
    
    }
    
    func testflowtest() {
        register()
        testSignUp()
    }
        
}

After running the testFlowTest function in Test file, "credentials file is not found" error is showing.

I want to fill the Sign up text fields with name, email, password from the JSON file.

This is the image showing the error after using
XCTFail("Error: \(error)")

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒浓于脸红 2025-01-18 10:54:39

您的 JSON 格式不正确。键和值需要有引号,键/值对需要用逗号分隔:

[
    {
        "name" : "Tom Harry",
        "email" : "[email protected]",        
        "password" : "tomharry123"    
    },
    
    {
        "name" : "Sam Billings",
        "email" : "[email protected]",
        "password" : "sambillings789"
    }
]

这是可粘贴到 Playground 中的代码,显示这是可解析的(如果将其替换为您的代码,则会失败并出现相同的错误)原始 JSON):

let data = """
[
    {
        "name" : "Tom Harry",
        "email" : "[email protected]",
        "password" : "tomharry123"
    },
    
    {
        "name" : "Sam Billings",
        "email" : "[email protected]",
        "password" : "sambillings789"
    }
]
""".data(using: .utf8)!

do {
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    print(json)
} catch {
    print(error)
}

Your JSON isn't properly formatted. Keys and values need to have quotes, and key/value pairs need to be separated by commas:

[
    {
        "name" : "Tom Harry",
        "email" : "[email protected]",        
        "password" : "tomharry123"    
    },
    
    {
        "name" : "Sam Billings",
        "email" : "[email protected]",
        "password" : "sambillings789"
    }
]

Here's code that is paste-able into a Playground that shows that this is parsable (and will fail with your same error if you replace it with your original JSON):

let data = """
[
    {
        "name" : "Tom Harry",
        "email" : "[email protected]",
        "password" : "tomharry123"
    },
    
    {
        "name" : "Sam Billings",
        "email" : "[email protected]",
        "password" : "sambillings789"
    }
]
""".data(using: .utf8)!

do {
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
    print(json)
} catch {
    print(error)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文