3

I have a lot of models in my project which are Decodable. I have to write tests to ensure their parsing from a json.

What I did is:

  1. Create a folder to store my mocked json files for tests.
  2. Create a BaseModelTests<T>: XCTestCase where T: Decodable where I have one method which load the json and try to parse the model.
  3. Create all needed classes to test each Decodable I have.
  4. Run the tests which are working fine.

The problem is that for some reason Xcode is not considering these tests as "code coverage", in fact I have the coverage set to 0% for the files I tested. How is it possible? enter image description here

Am I forgetting or wronging something or is simply Xcode unable to understand the abstraction?


Here's an example of my routine:

class BaseModelTests<T>: XCTestCase where T: Decodable {
    var model: T?
    var jsonFileName: String { return "" }

    func testParsingModel() {
        guard let path = Bundle(for: type(of: self)).path(forResource: jsonFileName, ofType: "json") else {
            XCTFail("Impossible to find the file \(jsonFileName).json needed to test \(T.self) initialization")
            return
        }

        do {
            let dataToDecode = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
            model = try JSONDecoder().decode(T.self, from: dataToDecode)
        } catch {
            XCTFail("Failed the initialization of \(T.self)")
        }

        XCTAssertNotNil(model)
    }
}
class MyClassTests: BaseModelTests<MyClass> {
    override var jsonFileName: String { return "MyClass" }

    override func testParsingModel() {
        super.testParsingModel()

        guard let model = model else { return }

        XCTAssertTrue(model.accepted)
    }
}

0 Answers0