gpt4 book ai didi

ios - 单元测试错误地从启动 View Controller 执行代码

转载 作者:搜寻专家 更新时间:2023-11-01 07:28:35 24 4
gpt4 key购买 nike

我有一个如下所示的简单结构,它是 iOS 应用程序的一部分:

struct Country: JSONObject {
let name: String!
let code: String!

static let nameKey = "name"
static let codeKey = "dial_code"

init?(_ json: [String: AnyObject]) throws {
guard let name = json[Country.nameKey] as? String else {
throw JSONError.InvalidTypeForKey(key: Country.nameKey)
}

guard let code = json[Country.codeKey] as? String else {
throw JSONError.InvalidTypeForKey(key: Country.codeKey)
}

self.name = name
self.code = code
}
}

我写了一个单元测试来测试这个类的初始化:

func testCorrectInitialisationOfCountry() {
let countryDict = [Country.nameKey: "England", Country.codeKey: "+44"]

do {
let country = try Country(countryDict)!
XCTAssert(countryDict[Country.nameKey] == country.name, "The country name does not match")
XCTAssert(countryDict[Country.codeKey] == country.code, "The country code does not match")
}
catch _ {
print("Initialisation of country failed with an exception")
}
}

我面临的问题是这个结构在我应用的第一个 View Controller 的 viewDidLoad() 方法中被初始化了几次。

出于某种原因,我在运行测试时调用了 viewDidLoad() 方法,并因此生成了不正确的代码覆盖率。下图显示了 Xcode 生成的单元测试统计信息。

enter image description here

数字“241”实际上应该只是“1”。另外 240 次,该行是从未接受测试的启动 View Controller 执行的。

如何停止执行 View Controller 代码?

提前致谢。

最佳答案

单元测试在您正在运行的应用程序的上下文中运行。

我认为你最好的选择是编写你的应用程序委托(delegate)的 didFinishLaunchingWithOptions 如果通过测试启动(或启动一个更简单的),则不启动 View Controller

此答案提供了一种检查您的应用是否在单元测试中运行的方法:

https://stackoverflow.com/a/30306450/3937

要停止第一个 Storyboard的自动加载,请将其作为启动 Storyboard删除并按照以下答案自行编写加载代码:

https://stackoverflow.com/a/16702730/3937

关于ios - 单元测试错误地从启动 View Controller 执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34231768/

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