Reputation: 1953
I want to unit test a function that returns a function. This is a simplified example:
func someFunction(flag: Bool) -> () -> Void {
if flag {
return { print("True") }
} else {
return { print("False") }
}
}
What would be the best approach?
Other languages offer a toString
option, where you could check the string representation, but Swift prints "(Function)"
if I were to do something like:
let output = someFunction(flag: true)
print(output)
Upvotes: 1
Views: 718
Reputation: 63271
Other languages offer a
toString
option, where you could check the string representation
You wouldn’t actually want this, even if it were possible.
By analogy, would you ever write a test like this?
test() {
XCTAssertEqual(someFunction.toString(), """
func someFunction(flag: Bool) -> () -> Void {
if flag {
return { print("True") }
} else {
return { print("False") }
}
}
""")
}
The problem of course is that such a test doesn’t actually test anything, at all!
You should be testing the behaviour of the returned closure, just like any other SUT.
Upvotes: 2