OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 maxConcurrentOperationCount 对 NSOperationQueue 进行单元测试 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:59
标题: ios - 使用 maxConcurrentOperationCount 对 NSOperationQueue 进行单元测试

我有一个类,它是 NSOperationQueue 的一种包装器。它允许使用 block 将网络请求排入队列。当前请求是一个接一个地执行,但是将来可以更改。

下面是 MyRequestsQueue 类的代码:

@interface MyRequestsQueue ()

@property(nonatomic, strong) NSOperationQueue* queue;

@end

@implementation MyRequestsQueue

-(instancetype)init
{
    self = [super init];
    if(!self) {
        return nil;
    }

    self.queue = [[NSOperationQueue new] autorelease];
    self.queue.maxConcurrentOperationCount = 1;

    return self;
}

-(void)addRequestBlockvoid (^)())request
{
    NSBlockOperation* operation = [NSBlockOperation blockOperationWithBlock:request];
    [self.queue addOperationperation];
}

@end

一般来说,我知道如何使用 XCTest 对异步代码进行单元测试。但现在我想为 MyRequestsQueue 添加一个单元测试,以检查队列当时是否只执行一个操作。甚至更好 - 测试当前执行的操作数不大于 maxConcurrentOperationCount。我试图观察 self.queueoperationCount 属性,但是 documentation说我不应该依赖它。我怎样才能实现它?

编辑:我的测试使用以下模式:

@interface MessageRequestQueueTest : XCTestCase

@property(nonatomic, strong) MessageRequestsQueue* reuqestQueue;
@property(nonatomic, assign) NSInteger finishedRequestsCounter;

@end
// setUp method ommited - simply initializes self.requestQueue


-(void)testAddedRequestIsExecuted
{
    [self.reuqestQueue.queue setSuspended:YES];

    __weak __typeof(self) weakSelf = self;
    [self.reuqestQueue addRequestBlock:^{
        ++weakSelf.finishedRequestsCounter;
    } withName:kDummyRequestName];

    [self.reuqestQueue.queue setSuspended:NO];

    WAIT_WHILE(0 == self.finishedRequestsCounter, 0.1);
    XCTAssertEqual(self.finishedRequestsCounter, 1, @"request should be executed");
}

WAIT_WHILE 宏来自 AGAsyncTestHelper .



Best Answer-推荐答案


我建议您重新考虑您的测试策略。

But now I want to add a unit test for MyRequestsQueue that checks if queue executes only one operation at the time. Or even better - test that number of currently executing operations is not greater than maxConcurrentOperationCount.

这两个测试都将测试 Apple 的 NSOperationQueue 实现,这不会为您带来任何好处。你不想成为你不拥有的单元测试代码,通常你应该假设苹果已经正确地测试了他们自己的代码。如果 NSOperationQueue 运行的并发操作比它应该运行的多,Apple 就会有大问题!

相反,我只是测试一下,在它被初始化之后,您的 MyRequestsQueue 已在其 NSOperationQueue 上设置了正确的 maxConcurrentOperationCount

关于ios - 使用 maxConcurrentOperationCount 对 NSOperationQueue 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21229905/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4