2

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

这是 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)addRequestBlock:(void (^)())request
{
    NSBlockOperation* operation = [NSBlockOperation blockOperationWithBlock:request];
    [self.queue addOperation:operation];
}

@end

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

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

@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

4

2 回答 2

4

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

但是现在我想为 MyRequestsQueue 添加一个单元测试,以检查队列当时是否只执行一个操作。甚至更好 - 测试当前执行的操作数不大于 maxConcurrentOperationCount。

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

相反,我会简单地测试一下,在它被初始化之后,你MyRequestsQueue已经maxConcurrentOperationCount在它的NSOperationQueue.

于 2014-01-20T11:37:11.563 回答
1

会有帮助吗?检查count财产。

@interface MyRequestsQueue ()

@property(nonatomic, strong) NSOperationQueue* queue;
@property(assign) NSUInteger count ;

@end

@implementation MyRequestsQueue

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

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

    return self;
}

-(void)addRequestBlock:(void (^)())request
{
    NSBlockOperation* operation = [NSBlockOperation blockOperationWithBlock:^{
        ++self.count ;
        request() ;
        --self.count ;
    }] ;
    [self.queue addOperation:operation];
}

@end
于 2014-01-20T09:31:45.030 回答