In unit test, execute a block queued with dispatch_asyc

If I dispatch_asyncblock in the main queue:

-(void) myTask {
  dispatch_async(dispatch_get_main_queue(), ^{
      [self.service fetchData];
   });
}

In unit test, I can execute the block passed in the main queue, manually start the main loop as follows:

-(void)testMyTask{
  // call function under test
  [myObj myTask];
  // run the main loop manually!
  [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
  // now I can verify the function 'fetchData' in block is called
  ...
}

Now I have another similar function that sends a block to the next queue , different from :

-(void) myTask2 {
  dispatch_async(dispatch_queue_create("my.sequential.queue", NULL), ^{
      [self.service fetchData];
   });
}

In unit test, how can I execute a block manually now?

-(void)testMyTask2{
  // call function under test
  [myObj myTask2];
  // How to manually execute the block now?
}

=== Refine ===

, , , - Wait-For-Timeout. , . , ( , ), .

+1
2

.

-(void) myTask2:(dispatch_queue_t*)queue {
    dispatch_async(*queue, ^{
        [self.service fetchData];
    });
}

-(void)testMyTask2{
    dispatch_queue_t queue = dispatch_queue_create("my.sequential.queue", NULL);
    [myObj myTask2:&queue];

    dispatch_sync(queue, ^{
    });
}

( currentRunLoop )

+1

XCTestExpectation class

-(void) myTask2 {
  XCTestExpectation *expectation = [self expectationWithDescription:@"catch is called"];
  dispatch_async(dispatch_queue_create("my.sequetial.queue", NULL), ^{
      [self.serviceClient fetchDataForUserId:self.userId];
      [expectation fulfill];
   });

   [self waitForExpectationsWithTimeout:Timeout handler:^(NSError *error) {
        //check that your NSError nil or not
    }];
}

0

Source: https://habr.com/ru/post/1654365/


All Articles