Check if current unit test code works or not

I want to check if the executable code is a tese case block or does not execute other code for the result, for example:

if ( unit test case is running ) { do something } else { do other thing } 

any idea on this?

+5
source share
4 answers

This is a bad approach, you should try to simulate the logical parts that you are trying to avoid with this statemetn via Mock or another mechanism.

Now for your question, you can use the oolean variable, such as isUnittest , which you set when setting up the test and Teardown, ut as indicated, I do not recommend you to do this.

+3
source

Do not tell UIAlertView directly. Use dependency injection instead, such as a property of type

 @property (strong, nonatomic) Class alertViewClass; 

Then your alert notification code can do

 UIAlertView *alert = [[_alertViewClass alloc] initWithTitle:…etc…]; 

In your test code, enter another class. I am using https://github.com/jonreid/JMRTestTools to indicate JMRMockAlertView . Then I can check call alerts with JMRMockAlertViewVerifier . (In fact, this allows you to create alerts based on testing.)

Change: these days I'm using https://github.com/jonreid/ViewControllerPresentationSpy

+1
source

Another way is to let the class customize the behavior controlled by the static method and have a test call that calls this method in its static load method.

I had a similar problem using storyboards and an external sedative service for authentication through oauth. The application delegate will check if appdelegate has a valid oauth token: didFinishLaunchingWithOptions, and if not, programmatically run segue to log in to oauth. But this was undesirable in test cases. To solve this problem, I created a static method in the application delegate to disable the login screen. This is the code inside my application delegate:

 static Boolean showLoginScreen = TRUE ; + (void) disableLoginScreen { showLoginScreen = FALSE ; NSLog(@"disabled login screen") ; } 

In the test example, the boot method was set:

 // disable login screen for the test case + (void) load { NSLog( @"now disabling login screen" ) ; [XYZAppDelegate disableLoginScreen]; } 

This worked because the test case class was loaded before the application was initialized. Of course, you should check the value of this flag in the application delegate in order to start / not start the login. Other alternatives that I tried but rejected were as follows:

+1
source

This works for me (iOS 8, Xcode 6):

 - (BOOL) isRunningTest { return NSClassFromString(@"XCTestCase") != nil; } 

I think this is cleaner and easier than other answers.

+1
source

All Articles