Search code examples
xctestxctestcase

Why isn't +setup in my testcases being called when I create a custom test suite with XCTest?


I have a subclass of XCTestSuite that I instantiate and populate with tests on the fly:

+ (XCTestSuite *)defaultTestSuite {
    MySuite *suite = [[MySuite alloc] initWithName:@"suite"];
    [suite addTest:[[MyTestCase alloc] initWithSelector:@selector(firstTest)]];
    [suite addTest:[[MyTestCase alloc] initWithSelector:@selector(secondTest)]];
    return suite;
}

+ (void)setUp {}
- (void)setUp {}
- (void)firstTest {}
- (void)secondTest {}

The -(void)setUp is being called for each test, but +(void)setUp is never called. If I don't use my custom testSuite or I call:

 + (XCTestSuite *)defaultTestSuite {
    XCTestSuite *suite = [super defaultTestSuite];
    [suite addTest:[[MyTestCase alloc] initWithSelector:@selector(firstTest)]];
    [suite addTest:[[MyTestCase alloc] initWithSelector:@selector(secondTest)]];

it does get called. Why is this?


Solution

  • XCTest has a private internal class called XCTestCaseSuite that is a subclass of XCTestSuite. You can see the Swift source here. It is what is responsible for calling +(void)setUp for you. If you want this same functionality, you will have to duplicate it in your custom XCTestSuite subclass. I couldn't find documentation for this anywhere, but it does make some sense in that if test cases are coming from different classes, how do you order when the +(void)setUp/+(void)tearDown methods are called.