【问题标题】:how to test something in nsthread如何在 nsthread 中测试一些东西
【发布时间】:2013-11-04 08:50:31
【问题描述】:

我想使用 OCUnit 来测试我的工作。 但我的一种方法是这样的:

- (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**********************");
} 

现在我要运行测试:

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

在我的测试用例中 但是thread2没有运行 所以我该怎么做?第三季!

【问题讨论】:

  • 我知道这只是一个代码示例,与您的问题无关,但在命名类时不要使用 thisNotation 而是使用 ThisNotation - 第一个字母应始终为大写。此外,局部变量名中的下划线也不合适,它通常用于实例变量。

标签: ios ocunit


【解决方案1】:

您可以使用dispatch_semaphore 使testThread 等到thread2 完成:

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多