0

I'm facing a strange problem with using NSLog in iOS's unit test.

The Code

Here is the test code I'm using in my unit test.

- (void)testExample
{
  NSOperationQueue *newqueue = [[NSOperationQueue alloc] init];
  NSURLRequest *request2 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.apple.com"]];

  dispatch_semaphore_t sema2 = dispatch_semaphore_create(0);
  [NSURLConnection sendAsynchronousRequest:request2 queue:newqueue completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
    //    NSLog(@"2: Data: %@", data);
    printf("2: Data: %s\n", [[data description] UTF8String]);
    dispatch_semaphore_signal(sema2);
  }];

  //  sleep(2);
  dispatch_semaphore_wait(sema2, DISPATCH_TIME_FOREVER);
  dispatch_release(sema2);

  NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
  NSOperationQueue *queue = [[NSOperationQueue alloc] init];

  dispatch_semaphore_t sema = dispatch_semaphore_create(0);
  [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
    NSLog(@"1: Data: %@", data);
    dispatch_semaphore_signal(sema);
  }];

  //  sleep(2);

  dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
  dispatch_release(sema);

  NSLog(@"Over");
}

To use the code

  1. Create a simple iOS project with Unit Test.
  2. Paste the code above to the xxxTest.m
  3. Press ⌘ + u

Patterns I tried

  1. Change the order of 2 different urls, for example let www.google.com run at first or let www.apple.com run at first.
  2. Change the use of dispatch_semaphore_xxx to sleep().
  3. Change NSLog() to printf()
  4. Run this code as a Cocoa console app.
  5. Remove the test of second URL request.

Results

  1. Running time 0.4s ~ 30s
  2. Running time 0.4s ~ 30s
  3. Running time 0.4s ~ 30s
  4. Running time ~0.4s
  5. Running time ~0.4s

Questions

  1. What is happening when I try the first 3 patterns?
  2. Do you have a similar problem with you?
  3. Are there any solutions to these?

Thank you guys!

4

1 回答 1

0

这是 SenTest 和 NSLog 的问题。基本上,日志通过管道传送到测试运行程序,该运行程序将数据发送回 XCode 中的控制台窗口。

NSLog 写入 stderr,因此如果将其重定向到文件,则可以获取日志数据。

不幸的是,当一切都完成后,仍然需要一段时间才能将其全部写回。

如果我需要在测试期间记录一堆数据,我会将 stderr 重定向到一个文件,然后在测试运行时“tail -f”它,如果我想看它滚动的话。结束后,我可以在 mvim 或 XCode 中查看该文件。

于 2012-08-08T14:40:48.393 回答