以编程方式确定iOS项目中的当前目标(运行或testing)
有没有什么办法可以通过编程来确定在开发iOS应用程序时是否在testing目标和常规运行目标中运行代码?
我有检查如果这个variables为零或不是因为它只是在我的testing目标的黑客攻击,但这似乎很hacky。
[[[NSProcessInfo processInfo] environment] objectForKey:@"XCInjectBundle"]
您应该在“目标设置”中为“预处理器macros”定义适当的值。
在运行时你可以用ifdef
语句来检查它。
这些答案都没有帮助我。 我希望我的应用程序能够知道何时运行testing,以限制testing目标中的日志logging。 当我不logging一堆东西时,testing运行得更快。 所以,我通过向我的scheme的testing部分添加一个自定义参数来做到这一点:
在我的应用程序代码中,我现在可以检查是否正在testing:
- (void)logError:(NSError*)error{ if([[[NSProcessInfo processInfo] arguments] containsObject:@"-FNTesting"]) return; NSLog(@"LOG THE ERROR"); }
感谢@cameronspickert是唯一可以find如何使用自定义参数的地方之一
http://cameronspickert.com/2014/02/18/custom-launch-arguments-and-environment-variables.html
在Xcode 7.3上testing
在NSProcessInfo
上创build一个类别。
@implementation NSProcessInfo (RunningTests) - (BOOL)ag_isRunningTests { return ([self.environment objectForKey:@"XCTestConfigurationFilePath"] != nil); } @end
现在我们可以简单地用“ UITesting ”的一行代码来检查 。
[[[NSProcessInfo processInfo] arguments] containsObject:@"-ui_testing"]
-ui_testing只会在testing应用程序时出现。
在Xcode 6中,您可以在环境variables中检查XPC_SERVICE_NAME
的值,以查看模拟器是直接运行testing还是应用程序。
直接运行时,variables将具有像UIKitApplication:com.twitter.FabricSampleApp[0xb9f8]
运行unit testing时,它将如下所示: com.apple.xpc.launchd.oneshot.0x10000008.xctest
+ (BOOL)isRunningUnitTests { NSString *XPCServiceName = [NSProcessInfo processInfo].environment[@"XPC_SERVICE_NAME"]; BOOL isTesting = ([XPCServiceName rangeOfString:@"xctest"].location != NSNotFound); return isTesting; }
谢谢! 它有助于。 下面是一些关于swift的例子:
func isRunningTests() -> Bool { var arguments = NSProcessInfo.processInfo().arguments as! [String] println("arguments ===\(arguments)") let testArgs = arguments.filter({ $0 == "-FNTesting" }) if !testArgs.isEmpty { return true } return false }
在项目设置的“信息”选项卡上,创build一个新的configuration(除了默认的“debugging”和“发布”)。 然后,您将能够在每个configuration的基础上,在目标设置(在“构build设置”选项卡上)中定义不同的预处理器macros。 XCode已经使用它来为Debugconfiguration添加“DEBUG = 1”,这使您可以在代码中使用“#ifdef DEBUG”。 你可以像这样添加任何其他的macros,比如“TESTING = 1”。
谢谢@ steven-hepting,你的回答帮助我指出了正确的方向来解决我的问题。
但是当在你的unit testing中使用“Host Application”的时候,“XPC_SERVICE_NAME”会返回与正常的app start相同的string(很明显)。 所以你的支票单独并不总是工作。 这就是为什么我另外还要检查TestBundleLocation
。 用Xcode 7.2(7C68)进行testing。
+ (BOOL)isRunningUnitTests { NSDictionary<NSString *, NSString *> *env = [NSProcessInfo processInfo].environment; // Library tests NSString *envValue = env[@"XPC_SERVICE_NAME"]; BOOL isTesting = (envValue && [envValue rangeOfString:@"xctest"].location != NSNotFound); if (isTesting) { return YES; } // App tests // XPC_SERVICE_NAME will return the same string as normal app start when unit test is executed using "Host Application" // --> check for "TestBundleLocation" instead envValue = env[@"TestBundleLocation"]; isTesting = (envValue && [envValue rangeOfString:@"xctest"].location != NSNotFound); return isTesting; }