简体   繁体   English

在XCtest类中使用覆盖init()?

[英]Using override init() in an XCtest class?

I'm wondering if there is a way to use unit when XCtesting in order to specify a constant variable that isn't torn down between separate test cases? 我想知道在XCtesting中是否有办法使用单位来指定一个在不同测试用例之间没有拆除的常量变量? I realize that generally best practices for unit testing are to keep the tests as self contained as possible but in my current situation it would make the tests execute a lot faster if I were able to do this and keep a constant variable between test cases. 我意识到,通常单元测试的最佳实践是尽可能保持测试的自包含,但在我目前的情况下,如果我能够做到这一点并在测试用例之间保持一个恒定的变量,它将使测试执行得更快。

Currently, any type of init function that I call 目前,我调用的任何类型的init函数

override init() {
    super.init()
}

Leaves me with an EXC_BAD_INSTRUCTION error. 给我留下了EXC_BAD_INSTRUCTION错误。 If I can't use init() in XCTestCase, is there another work around that I can use? 如果我不能在XCTestCase中使用init(),我还可以使用另一种解决方法吗?

Try moving the variable outside of the XCTestCase class. 尝试将变量XCTestCase类之外。

import XCTest

var counter = 0 // Note this is outside the class declaration

class MyTests: XCTestCase {
    override func setUp() {
        super.setUp()
        counter++
        print("Counter: \(counter)")
    }

    func testOne() {
        ...
    }

    func testTwo() {
        ...
    }

    func testThree() {
        ...
    }
}

This gives an output like this. 这给出了这样的输出。

...
Counter: 1
...
Counter: 2
...
Counter: 3
...

You can use the class setUp and tearDown methods for exactly this purpose. 您可以使用 setUptearDown方法来实现此目的。 The class setUp method is called once before the first test method begins and the class tearDown method is called once after all test methods have completed. 在第一个测试方法开始之前调用类setUp方法,并在所有测试方法完成后调用类tearDown方法一次。

My understanding is that these are intended precisely for handling the kind of test-wide state you describe. 我的理解是,这些只是为了处理您描述的测试范围的状态。 Apple has some good documentation on it. Apple有一些很好的文档

The advantage of this approach is that the state is at least kept local to the test class, if not the individual tests. 这种方法的优点是,如果不是单独的测试,状态至少保持在测试类的本地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM