gpt4 book ai didi

swift - 使用 PACT 的 XCUITest 不返回模拟网络响应

转载 作者:行者123 更新时间:2023-11-28 08:16:14 27 4
gpt4 key购买 nike

我正在尝试使用 PACT Consumer Swift 运行 XCUITest并且无论我如何尝试配置它,都会发出真实的网络请求,而不是接收带有 200 状态代码和 X-Auth-Token 的模拟响应。我错过了什么?

这是 UI 测试用例:

import XCTest
import PactConsumerSwift
import Nimble

class MyFeature: XCTestCase {

override func setUp() {
super.setUp()
let app = XCUIApplication()
app.launchArguments = ["FeatureTest"]
app.launch()
Nimble.AsyncDefaults.Timeout = 60
}

override func tearDown() {
super.tearDown()
}

func testSuccessfulSignIn() {
let API = MockService(
provider: "Sign In API",
consumer: "Sign In Consumer")

API
.given("user signs in with valid credentials")
.uponReceiving("valid credentials")
.withRequest(method: .POST,
path: "/login",
body: [
"username": "john",
"password": "1234"
])
.willRespondWith(
status: 200,
headers: [
"X-Auth-Token":"Super-Cool-Token"
])

API.run { (testComplete) in
let app = XCUIApplication()

let usernameField = app.textFields["UsernameField"]
usernameField.tap()
usernameField.tap()
usernameField.typeText("john")

let passwordField = app.secureTextFields["PasswordField"]
passwordField.tap()
passwordField.typeText("1234")

app.buttons["LOGIN"].tap()

expect(app.staticTexts["Welcome!"].exists).to(beTrue())

testComplete()
}
}

}

这是实际的登录逻辑:

func attemptLogin(_ user:String? = nil, password:String? = nil) -> Promise<LoginResponse> {
if let
baseUrl = URLService.getBaseUrl(),
let url = URL(string: baseUrl + "login")
{
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

if
let username = encode(string: user),
let password = encode(string: password)
{
request.httpBody = "username=\(username)&password=\(password)".data(using: String.Encoding.utf8)
}
}

// Sends request and does other stuff...
}

最佳答案

实例化 MockServer 类会在后台启动模拟服务器。它运行的 url 将在 MockServer 实例上可用。在您的示例中,这将是 API.baseUrl

您需要将被测应用配置为与此 url 通信(即您希望 URLService.getBaseUrl() 返回模拟服务器的 url)。也许您可以通过启动参数或环境传递 url,例如app.launchArguments = ["FeatureTest", API.baseUrl]

关于swift - 使用 PACT 的 XCUITest 不返回模拟网络响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42517432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com