Search code examples
iosocunit

how to test something in nsthread


I want to use OCUnit to test my work. but one of my methodes is like this:

- (BOOL)testThread
{
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread) object:nil];
    [thread start];

    return YES;
}

- (void)thread
{
    NSLog(@"thread**********************");
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread2) object:nil];
    [thread start];
}

- (void)thread2
{
    NSLog(@"thread2**********************");
} 

Now I want to run the test:

- (void)testExample
{
    testNSThread *_testNSThread = [[testNSThread alloc] init];
    STAssertTrue([_testNSThread testThread], @"test");
}

in my test case but the thread2 dose not run so,what should I do? 3Q!


Solution

  • You can use dispatch_semaphore to make testThread wait until thread2 has completed:

    @interface MyTests () {
        dispatch_semaphore_t semaphore;
    }
    
    @implementation MyTests 
    
    - (void)setUp 
    {
        [super setUp];
        semaphore = dispatch_semaphore_create(0);
    }
    
    - (BOOL)testThread
    {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread) object:nil];
        [thread start];
    
        // Wait until the semaphore is signaled
        while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
        }
    
        return YES;
    }
    
    - (void)thread
    {
        NSLog(@"thread**********************");
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread2) object:nil];
        [thread start];
    }
    
    - (void)thread2
    {
        NSLog(@"thread2**********************");
    
        // Signal the semaphore to release the wait lock
        dispatch_semaphore_signal(semaphore);
    }
    
    @end