Inherit tests from a common XCTestCase from a Swift package

Viewed 57

Consider the following: A Swift package Feature has a protocol Component and a couple of implementations FooComponent, BarComponent, etc. The package has its own tests FeatureTests and the Component's are tested in a way, that individual implementations inherit a single test case in order to test the common expectations of a Component:

import XCTest
@testable import Feature

class ComponentTests: XCTestCase {
  var sut: Component!
  
  override class var defaultTestSuite: XCTestSuite {
    XCTestSuite(name: "EventStorageService Interface Tests Excluded")
  }

  func test_common() { }
}

...

class FooComponentTests: ComponentTests {
  override func setUpWithError() throws {
    try super.setUpWithError()
    sut = FooComponent()
  }
  
  override class var defaultTestSuite: XCTestSuite {
    XCTestSuite(forTestCaseClass: Self.self)
  }

  func test_specific() { }
}

class BarComponentTests: ComponentTests {
  override func setUpWithError() throws {
    try super.setUpWithError()
    sut = BarComponent()
  }

...

This all works really nicely within the Swift package.

Now let's consider the app App injects its own custom Component implementation and also wants to test it and benefit from the already written common tests.

import XCTest
@testable import App
@testable import Feature

class CustomComponentTests: ComponentTests { // Error: Cannot find type 'ComponentTests' in scope
...

Of course the above does not work as the compiler does not find ComponentTests. And importing FeatureTests also fails.

import XCTest
@testable import App
@testable import FeatureTests // Error: No such module 'FeatureTests'

class CustomComponentTests: ComponentTests {
...

Does anyone have an idea how to achieve the desired outcome (i.e. inherit common tests for the protocol defined within the lib in order to not duplicate the test code)?

0 Answers
Related