CiNN
CiNN

Reputation: 9870

How to test swift nested function?

How do you write test for swift nested function?

Since the function is inside another function, I don't know how to call it from outside.

I'm using nested function because I can't call a private self function in init

Upvotes: 1

Views: 819

Answers (2)

Rob Napier
Rob Napier

Reputation: 299345

Continuing the point from Code Different, from a testing point of view, the following code is identical:

// Without nesting
func f() {
    // Do things
    // Do other things we want to test
    // Do more things
}

// With nesting
func fnest() {
    func nest() {
        // Do other things we want to test
    }

    // Do things
    nest()
    // Do more things
}

Whatever technique you'd use to test "Do other things we want to test" in f() is precisely the same technique that you'd use to test it in fnest(). If the piece you want to test is insufficiently accessible, in either case you must redesign (or change your testing goal), but there's nothing special about nested functions.

I'm using nested function because I can't call a private self function in init

If this is the entire problem, then make the function static and pure. Rather than passing self, pass the data required to perform the calculation, and return the result. Then modify self inside of init rather than in the function.

Upvotes: 3

Code Different
Code Different

Reputation: 93171

You shouldn't test nested function, just like you shouldn't test private methods, from Bad Testing Practices:

Private means private. Period. If you feel the need to test a private method, there is something conceptually wrong with that method. Usually it is doing too much to be a private method, which in turn violates the Single Responsibility Principle.

Upvotes: 4

Related Questions