gpt4 book ai didi

swift - XCTestCase 可选实例变量

转载 作者:搜寻专家 更新时间:2023-10-31 22:10:16 25 4
gpt4 key购买 nike

为什么我的可选实例变量是 nil,而实际上我将它设置为非 nil?

代码:

class FooTests: XCTestCase {
var foo: Int?

func test_A_setFoo() {
XCTAssertNil(foo)
foo = 1
XCTAssertNotNil(foo)
}

func test_B_fooIsNotNil() {
XCTAssertNotNil(foo)
}
}

test_A_setFoo()成功,而 test_B_fooIsNotNil() 失败

最佳答案

来自 Flow of Test Execution(强调):

For each class, testing starts by running the class setup method. For each test method, a new instance of the class is allocated and its instance setup method executed. After that it runs the test method, and after that the instance teardown method. This sequence repeats for all the test methods in the class. After the last test method teardown in the class has been run, Xcode executes the class teardown method and moves on to the next class. This sequence repeats until all the test methods in all test classes have been run.

在您的例子中,test_B_fooIsNotNil() 在新实例上执行,foo 属性为 nil

常用设置代码可以放到setUp()类方法中或 setUp() 实例方法,参见 Understanding Setup and Teardown for Test Methods

关于swift - XCTestCase 可选实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48562711/

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