Mimic
Mimic
是一个用于模拟网络请求的简单库。
集成
Cocoapods
使用 Mimic
与 Cocoapods。
要将 Mimic
集成到您的Xcode项目中,请在您的 Podfile
中添加以下内容。
pod 'Mimic', '~> 1.3.1'
Swift包管理器
使用 Mimic
与 Swift包管理器。
在您的 Package.swift
文件中将 Mimic
设置为依赖项。
dependencies: [
.package(url: "https://github.com/feliperuzg/Mimic", .upToNextMajor(from: "1.3.1"))
]
Carthage
使用 Mimic
配合 Carthage。
要将 Mimic
集成到您的 Xcode 项目中,请在您的 Cartfile
中添加以下内容。
github "feliperuzg/Mimic"
使用方法
添加新的存根
要创建一个新的存根,使用
@discardableResult public class func mimic(
request: @escaping MimicRequest,
delay: TimeInterval = 0,
response: @escaping MimicResponse
) -> MimicObject
其中 MimicRequest
构建方式如下
request(with method: MimicHTTPMethod, url: String, wildCard: Bool = false)
而 MimicResponse
构建方式如下
response(with json: Any status: Int = 200, headers: String : String]? = nil)
示例
let stub = Mimic.mimic(
request: request(with: .get, url: "http://example.com"),
delay: 2,
response: response(with: ["response": true], status: 200, headers: ["SomeHeader": "SomeValue"])
)
您可以选择不存储返回的 MimicObject
,如下
Mimic.mimic(
request: request(with: .get, url: "http://example.com"),
delay: 2,
response: response(with: ["response": true], status: 200, headers: ["SomeHeader": "SomeValue"])
)
随机化存根
Mimic
支持返回相同请求的随机模拟对象,要实现此功能,为同一请求添加多个模拟对象,例如
Mimic.mimic(
request: request(with: .get, url: "http://example.com"),
delay: 2,
response: response(with: ["response": true], status: 200])
)
Mimic.mimic(
request: request(with: .get, url: "http://example.com"),
delay: 2,
response: response(with: ["response": false], status: 400])
)
最后,通过激活 Mimic
的参数来激活随机化功能
Mimic.randomizeMimics = true
这将搜索所有模拟对象以请求,并返回随机元素。
使用通配符参数
Mimic
支持在 URL 中添加多个通配符参数,通过将字符串替换为 @wild
来实现。这允许存根对路径或查询中的动态参数进行存根,例如
以下面的 URL 为例
http://example.com/path1/path2?item1=value1&&item2=value2
将通配符参数添加到路径参数 path2
http://example.com/path1/
@wild?item1=value1&&item2=value2
将通配符参数添加到查询参数 value1
http://example.com/path1/path2?item1=
@wild&&item2=value2
同时将通配符参数添加到 path2
和 value1
http://example.com/path1/
@wild?item1=
@wild&&item2=value2
移除桩
要移除单个桩,可以使用以下方式
public class func stopMimic(_ mimic: MimicObject)
例如
这将添加一个新的桩
let stub = Mimic(
request: request(with: .get, url: "http://example.com"),
delay: 2,
response: response(with: ["response": true))
)
要移除它,您将执行以下操作
Mimic.stopMimic(stub)
要移除所有桩,请调用
Mimic.stopAllMimics()
测试
为确保在请求之前执行 URLSessionConfiguration
混淆,建议首先初始化 Mimic
class myTests: XCTests {
...
// Test properties here
override func setUp() {
super.setUp()
Mimic.start()
...
// Other initializers
}
...
// Other tests functions
}
限制
Mimic
仅支持简单的请求,目前还不支持下载或上传任务。
请求方法限制为
- GET
- POST
- DELETE
- PUT