What is the purpose of XCTestCase's setUp method?

故事扮演 提交于 2019-11-28 21:04:30
James Frost

There are a couple of points for discussion here: the behaviour of the setUp methods, and general best testing practices.

There are actually two setUp methods:

+ (void)setUp;
- (void)setUp;

The class method (+ (void)setUp) is only run once during the entire test run.

The instance method (- (void)setUp) is the one in the default template; it's run before every single test. Hopefully, in a hypothetical future version of Xcode, this comment will have been changed to // Put setup code here. This method is called before the invocation of each test method in the class. WINK WINK

So through these two methods, both of the behaviours you described are possible.

Regarding your comment:

"Surely developers aren't creating objects in it over and over?"

My answer would be "Yes, they usually are". A popular acronym for 'good' unit tests is FIRST:

  • Fast
  • Isolated
  • Repeatable
  • Self-Verifying
  • Timely

Isolated is key to this discussion: your tests shouldn't rely on any previous state left behind by other tests. Ideally, you should tear down and recreate your in-memory Core Data stack for every test, so you know that you're starting from a clean slate. A good example is in this post by Graham Lee. You want to use an in-memory stack because a) you can easily throw it away, and b) it should be very fast because it's just in-memory and not hitting your disk.

If you find that your tests are running slowly as a result of this (don't optimize prematurely), then I think a reasonable next step would be to create the stack in your + (void)setUp method, but create a brand new context every time in your - (void)setUp method.

I came here with almost the same problem: how to perform the setUp just once and in Swift. Here is the solution:

override class func setUp() {
    super.setUp()    
    // ...
}

override class func tearDown() {    
    // ...
    super.tearDown()
}

Right now I'm still looking for a solution for an asynchronous setUp!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!