Xcode project how to detect target programmatically or how to use env vars

Viewed 22218

I want to do an Application test that parses some json, stores to core data, and reads out some objects.

How can my code know if it's being run as part of a test or normal run? Just some way to know "are we in test target"? Because the app when it fires up now kicks off a bunch of requests to populate my coredata with info from the server. I don't want it to do this during my tests. I want to fire up the App, read HARDCODED json from a file and store this using the same methods as otherwise into coredata, and verify the results.

If someone could explain how to pass specific key-value pairs on a per target basis that can be read from within the app, I would be even more delighted.

5 Answers

Usually in Unit Test programmers are using mocking classes and functionalities. You can create a class with target membership only for the test target.

@interface MockClass : NSObject

@end

Target Membership Screenshot

Then in the application code you can check if class exist using NSClassFromString function (which will return Nil for target not included in the class's target membership, in this case - non test target.

if (NSClassFromString(@"MockClass")) {
    //Test Target
} else {
    //App Target
}

And you can of curse function it

BOOL isUnitTest(){
    return NSClassFromString(@"MockClass") != Nil;
}
Related