Bill
Bill

Reputation: 45408

How do I set up unit tests in Swift?

I'm having trouble adding unit tests to a Swift project of mine, so I created a fresh Xcode test project with a stripped-down version of my class:

class SimpleClass {
    let x: String

    init(x: String) {
        self.x = x
    }

    convenience init(dict: Dictionary<String, String>) {
        self.init(x: dict["x"]!)
    }
}

Then I created a simple test case:

import XCTest
import TestProblem

class TestProblemTests: XCTestCase {
    func testExample() {
        // This is an example of a functional test case.
        XCTAssertEqual(SimpleClass(x: "foo"), SimpleClass(dict: ["x": "foo"]))
    }

}

I had to import the project itself (import TestProblem) to fix unresolved identifier errors for SimpleClass.

However, when I try to run tests, I get the following compiler error:

Could not find an overload for 'init' that accepts the supplied arguments

What am I missing here? The calls to init work fine outside of the XCTAssertEqual call, even within the test file.

On a hunch, I also tried:

    let x = SimpleClass(x: "foo")
    let y = SimpleClass(dict: ["x": "foo"])
    XCTAssertEqual(x, y)

When I do that, I get this error:

Cannot convert the expression's type 'Void' to type 'SimpleClass'

Upvotes: 4

Views: 1753

Answers (1)

jaumard
jaumard

Reputation: 8292

Did you try to define your param explicitely ? Like this :

let x : SimpleClass = SimpleClass(x: "foo")
let y : SimpleClass = SimpleClass(dict: ["x": "foo"])
XCTAssertEqual(x, y)

Upvotes: 3

Related Questions