gmoraleda
gmoraleda

Reputation: 1953

Swift: How to unit test a function returning a function?

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

Answers (1)

Alexander
Alexander

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!

  1. It makes no specific claims as to the desired functionality of the system under test (SUT), so it’s not useful as a specification of your system
  2. It’s no simpler than the SUT it tests, meaning it gives you no confidence that you didn’t just make the same mistake twice.
  3. It’s also incredibly brittle, in any tiny refactoring of the implementation code will needlessly break the test, even if the refactoring made no behavioural changes. That’s the worst kind of test, because it’s expensive to maintain over time.

You should be testing the behaviour of the returned closure, just like any other SUT.

Upvotes: 2

Related Questions