我也有同样的问题。我的解决方案类似但不完全相同。首先,我像这样创建了 Codable 结构
import Foundation
struct AwsConfiguration: Codable {
struct S3TransferUtility : Codable {
private enum CodingKeys: String, CodingKey {
case defaultConfig = "Default"
}
struct DefaultConfig : Codable {
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case region = "Region"
}
var bucket: String
var region: String
}
var defaultConfig: DefaultConfig
}
private enum CodingKeys: String, CodingKey {
case s3TransferUtility = "S3TransferUtility"
}
var s3TransferUtility: S3TransferUtility
}
然后我定义了一个 DataHelper 类
final class DataHelper {
static func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
}
然后放入awsconfiguration.json
你的测试目标。然后你可以像这样写一个单元测试
func testReadAWSConfiguration() throws {
let config: AwsConfiguration = DataHelper.load("awsconfiguration.json")
print ("************config bucket: \(config.s3TransferUtility.defaultConfig.bucket) " +
"\n************config region: \(config.s3TransferUtility.defaultConfig.region)")
XCTAssertNotEqual("", config.s3TransferUtility.defaultConfig.bucket)
XCTAssertNotEqual("", config.s3TransferUtility.defaultConfig.region)
}