4

If I try this, it runs tests and success, all green-marked:

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 if you try to run tests for this:

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

    func testblablblblablba() {

    }
}


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

    override func testblablblblablba() {
    }
}

there 2 classes just ignored.

enter image description here

Does Testing support generics? Am I doing something wrong? Thanks for help)

Zaporozhchenko Oleksandr
  • 4,660
  • 3
  • 26
  • 48

1 Answers1

0

This is not supported in Xcode. After running tests with generics

class BaseTestClass<T>: XCTestCase {
    var subject: T!
}
class SpecializedTestCase: BaseTestClass<TestClass> {
    // Tests
}

they do not appear in the Report navigator in Xcode. However, no error or warning is thrown within Xcode and Xcode will appear to have run tests. Also, if code coverage is turned on, you will see the coverage display red.

However, I setup a case in a playground and it did execute the tests.

import XCTest

protocol Calculator {
    init()
    func add(a: Int, b: Int) -> Int
}

final class MyClass: Calculator {

    func add(a: Int, b: Int) -> Int {
        return a + b
    }

}

class BaseTestCase<T: Calculator>: XCTestCase {

    var subject: T!

    override func setUp() {
        super.setUp()
        subject = T()
    }

    func testShouldAdd() {
        XCTAssertEqual(subject.add(a: 2, b: 2), 4)
//        XCTAssertEqual(subject.add(a: 2, b: 2), 5)
    }
}

class TestCase: BaseTestCase<MyClass> {

}

TestCase.defaultTestSuite.run()

Test Output:

Test Suite 'TestCase' started at 2018-04-02 10:25:56.051
Test Case '-[__lldb_expr_26.TestCase testShouldAdd]' started.
Test Case '-[__lldb_expr_26.TestCase testShouldAdd]' passed (0.006 seconds).
Test Suite 'TestCase' passed at 2018-04-02 10:25:56.059.
     Executed 1 test, with 0 failures (0 unexpected) in 0.006 (0.008) seconds

If the second assert is uncommented, the tests will fail. My take on this is that the way test cases are registered in Xcode does not support the generic parameter, but if the test cases are registered manually, this can be supported.

Reference: https://medium.com/@johnsundell/writing-unit-tests-in-swift-playgrounds-9f5b6cdeb5f7

Eric
  • 54
  • 5