When I'm running unit tests, I'd like to skip some code (e.g. I don't want [[UIApplication sharedApplication] openURL:..]
to run). I'm looking for a runtime check if I'm currently running units tests or not.
I know I have seen code that checks the Objective-C runtime if unit tests are running but am not able to find it anymore.
Adding a unit test in Xcode If you already have a project, you can add a Unit Testing Bundle to it as well. Go to File > New > Target. Select iOS Unit Testing Bundle and then click Next.
⌘U will build and run all your test cases. It is the most commonly used shortcut when creating unit test cases. It is equivalent to ⌘R (build & run) while doing app development. You can use this shortcut to build your test target and run all the test cases in your test target.
Press Cmd+9 to open the report navigator, and look for “Coverage” under the most recent test run. This will show the code coverage data that was just collected – open the disclosure indicators so you can see inside User.
You can speed up your tests with parallel distributed testing. In this case, xcodebuild will distribute tests to each run destination by class. Each device then runs a single test class at a time.
You can use this method from google-toolbox-for-mac
// Returns YES if we are currently being unittested.
+ (BOOL)areWeBeingUnitTested {
BOOL answer = NO;
Class testProbeClass;
#if GTM_USING_XCTEST // you may need to change this to reflect which framework are you using
testProbeClass = NSClassFromString(@"XCTestProbe");
#else
testProbeClass = NSClassFromString(@"SenTestProbe");
#endif
if (testProbeClass != Nil) {
// Doing this little dance so we don't actually have to link
// SenTestingKit in
SEL selector = NSSelectorFromString(@"isTesting");
NSMethodSignature *sig = [testProbeClass methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setSelector:selector];
[invocation invokeWithTarget:testProbeClass];
[invocation getReturnValue:&answer];
}
return answer;
}
The reason that NSClassFromString
and NSInvocation
are used is to allow code compile without linking to xctest or ocunit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With