xcodeunit-testingswiftuiswift-testing

Why is Swift Testing not recognizing my helper function?


I just started diving into the new Swift Testing framework and I'm having an issue with the .enabled(if: Bool) trait.

My code below returns error Instance member 'accessTokenIsNil' cannot be used on type 'AuthorizationTests'; did you mean to use a value of this type instead? on the .enabled(if: accessTokenIsNil()) part.

import Testing
@testable import mews
import SwiftUI

struct AuthorizationTests {
    let accessTokenManager = AccessTokenManager()
    
    func accessTokenIsNil() -> Bool {
        accessTokenManager.token == nil
    }
    
    @Test("Get initial access token", .enabled(if: accessTokenIsNil()))
    func getAccessTokenSucces() {
        // continue test
    }
}

Below is from Apple's official documentation, so I'm not sure what I'm doing wrong.

func allIngredientsAvailable(for food: Food) -> Bool { ... }


@Test(
  "Can make sundaes",
  .enabled(if: Season.current == .summer),
  .enabled(if: allIngredientsAvailable(for: .sundae))
)
func makeSundae() async throws { ... }

Solution

  • The problem is that you can't access self in the @Test macro and if you look carefully at the examples in Apple's documentation they don't either since they don't have the test inside a type so both the function used for .enabled and the test functions are global.

    So either do the same and don't use struct AuthorizationTests {}

    let accessTokenManager = AccessTokenManager()
    
    func accessTokenIsNil() -> Bool {
        accessTokenManager.token == nil
    }
    
    @Test("Get initial access token", .enabled(if: accessTokenIsNil()))
    func getAccessTokenSucces() {
        // continue test
    }
    

    or make use of static properties and functions

    struct AuthorizationTests {
        static let accessTokenManager = AccessTokenManager()
    
        static func accessTokenIsNil() -> Bool {
            accessTokenManager.token == nil
        }
    
        @Test("Get initial access token", .enabled(if: accessTokenIsNil()))
        func getAccessTokenSucces() {
            // continue test
        }
    }