Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to detect if unit tests are running at runtime in Xcode?

Tags:

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.

like image 686
Ronald Mannak Avatar asked Jul 11 '14 00:07

Ronald Mannak


People also ask

How do I get unit test report in Xcode?

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.

How do I run unit test cases in Xcode?

⌘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.

How does Xcode measure test coverage?

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.

Does Xcode run tests in parallel?

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.


1 Answers

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

like image 190
Bryan Chen Avatar answered Oct 03 '22 21:10

Bryan Chen