Does XCTest supports Generics?

If I run below test, it succeeds, all test cases are marked green:

import XCTest


class SomeTestCaseSon: XCTestCase {
    override func setUp() {
        super.setUp()
    }

    func testblablblblablba() {
    }

}

class SomeTestCase: XCTestCase {
    override func setUp() {
        super.setUp()
    }

    func testblablblblablba() {
    }
}

class SomeGenericTestCase<T:NSObject>: XCTestCase {
    override func setUp() {
        super.setUp()
    }

    func testblablblblablba() {

    }
}

But when I try with the below code, the test succeeds but the test cases are not marked green. Also breakpoint won't work.

class SomeGenericTestCase<T: Decodable>: XCTestCase {
    override func setUp() {
        super.setUp()
    }

    func testblablblblablba() {

    }
}


class SomeTestCaseGeneral: SomeGenericTestCase<NSObject> {
    override func setUp() {
        super.setUp()
    }

    override func testblablblblablba() {
    }
}

Thanks in advance!

This may be relevant:

What version of Swift and which OS are you using?

Swift 5
Running on iPhone 14 Simulator with iOS version 16.2

This feature is only expected to work for specialized subclasses of generic subclasses of XCTestCase. So for example, in the following code:

struct Foo { ... }

class Parent<T>: XCTestCase { ... }
class Child: Parent<Foo> { ... }

only the test class Child and the test methods it contains will be run, since it is a subclass of Parent which specializes the generic T type to be the concrete type Foo.

It is not possible to run Parent on its own, because there is no information about what specific type to use for T and XCTest needs that in order to instantiate an instance of Parent.

3 Likes