이와 같이 테스트하려면 NSOperationQueue
을 테스트하고 싶을 것입니다.
테스트 할 클래스가 MySubject
이라고 가정합니다. 먼저, 리팩토링하여 NSOperationQueue
을 삽입하여 테스트 용으로 대체 할 수 있도록해야합니다. 따라서 [NSOperationQueue mainQueue]
의 모든 항목을 제거하고 클래스 변수로 바꾸십시오. MySubject
의 생성자에있는 매개 변수에서 해당 클래스 변수를 초기화하십시오. 따라서 MySubject
의 인스턴스를 모두 [NSOperationQueue mainQueue]
으로 변경해야합니다.
@interface MySubject: NSObject {
NSOperationQueue* operationQueue;
}
@end
@implementation MySubject
-(MySubject*)initWithOperationQueue:(NSOperationQueue*)queue {
if (self = [super init]) {
self.operationQueue = [queue retain];
}
return self;
}
-(void)dealloc {
[operationQueue release];
}
-(void)startOperations {
[operationQueue addOperation:...];
[operationQueue addOperation:...];
}
@end
그리고 클라이언트는 이제 다음과 같이 :
subject = [[MySubject alloc] initWithOperationQueue:[NSOperationQueue mainQueue]];
[subject startOperations];
이제 테스트를 위해, 당신은 테스트를위한 간단한 큐를 만들 수 있습니다 ... 그것은 당신의 주제에서 사용하는 어떤 방법을 구현해야합니다 .
물론
testQueue = [[MyTestOperationQueue alloc] init];
subject = [[MySubject alloc] initWithOperationQueue:testQueue];
[subject startOperations];
// You may want to have other tests that execute the queue operations
// in a different order
[[testQueue objectAtIndex:0] start];
[[testQueue objectAtIndex:0] waitUntilFinished];
[[testQueue objectAtIndex:1] start];
[[testQueue objectAtIndex:1] waitUntilFinished];
// Verify results
, 시험의 종류는 동시 작업을 동시에 수행 할 안전하다는 것을 확인할 수는 없지만이 :
@interface MyTestOperationQueue: NSMutableArray {
}
@end
@implementation MySubject
-(void)addOperation:(NSOperation*)operation {
[self addObject:operation];
}
@end
그리고 이제 테스트 캔은 다음과 같습니다 수업을 디자인 할 때 관심을 가질만한 많은 사례를 다룰 수 있습니다.
출처
2011-07-28 00:26:29
avh
NSBlockOperation/NSOperationQueue를 사용하여 멀티 스레딩을 구현하고 있습니다. – David
좋습니다. 스레드를 수동으로 생성하는 것은 최근에는 최적이 아닙니다. 그러나 코멘트는 여전히 유효하지만 동시 시스템에 대한 완전한 적용 범위를 얻는 것은 불가능하지만 전혀 테스트하지 않는 것보다 확실한 테스트를하는 것이 좋습니다! – bbum