XCTestCase 可选实例变量 [英] XCTestCase optional instance variable

查看:24
本文介绍了XCTestCase 可选实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is my optional instance variable nil when I infact set it to non-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() 失败

推荐答案

来自 测试执行流程(强调):

对于每个类,测试从运行类设置方法开始.对于每个测试方法,分配一个新的类实例并执行它的实例设置方法.之后它运行测试方法,然后运行实例拆卸方法.该序列对类中的所有测试方法重复.在类中的最后一个测试方法teardown 运行后,Xcode 执行类teardown 方法并移动到下一个类.这个顺序一直重复,直到所有测试类中的所有测试方法都运行完毕.

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.

In your case, test_B_fooIsNotNil() is executed on a fresh instance, for which the foo property is nil.

常见的设置代码可以放入setUp()类方法中或 setUp() 实例方法,见了解测试方法的设置和拆卸

Common setup code can be put into the setUp() class method or setUp() instance method, see Understanding Setup and Teardown for Test Methods

这篇关于XCTestCase 可选实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆