Search code examples
swiftxctest

How to use a user defined config variable as module name in @testable import in a swift test?


I have a user defined variable "MODULE_NAME_WITH_SUFFIX" that is different in every schema.

Now I need to import this module name in my tests, but don't know how.

Before I had a simple import:

@testable import MyApp

Now I want to use something like:

@testable import $(MODULE_NAME_WITH_SUFFIX)

Is this possible in Swift somehow?

Probably not, but is it maybe possible to import the module later programatically?


Solution

  • So far only this worked:

    In the Build settings of your project go to Active Compilation Conditions and add these fields to the schemes.

    Create one unique variable in each schema config:

    # in debug scheme 1
    DEBUG ABC_SCHEMA_ACTIVE
    
    # in debug scheme 2
    DEBUG XYZ_SCHEMA_ACTIVE
    
    # in debug scheme 3
    DEBUG
    
    # in release scheme 1
    ABC_SCHEMA_ACTIVE
    
    # in release scheme 2
    XYZ_SCHEMA_ACTIVE
    
    # in release scheme 3
    < nothing >
    

    No need to set a value for it, with #if you cannot compare the value.

    In the Build settings of the Test-Target you can use the MODULE_NAME_WITH_SUFFIX like this:

    # before
    TEST_HOST = "$(BUILT_PRODUCTS_DIR)/MyApp.app/MyApp";
    
    # after
    TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(MODULE_NAME_WITH_SUFFIX).app/$(MODULE_NAME_WITH_SUFFIX)";
    

    Then in every class derived from XCTestCase, instead of the normal import you add this monster:

    #if ABC_SCHEMA_ACTIVE
        @testable import MyAppABCSuffix
    #elseif XYZ_SCHEMA_ACTIVE
        @testable import MyAppXYZSuffix
    #else
        @testable import MyApp
    #endif
    

    Happy testing!