Weak delegate and OCMock
If you switch your Objective-C project to ARC or start a new project based on ARC you could use __weak
delegates. But if you try to mock them with OCMock, it fails.
Normal Delegate Mock with OCMock (no __weak)
id someDelegateMock = [OCMockObject mockForProtocol:@protocol(SomeWeakDelegate)];
[[someDelegateMock expect] someDelegateCall:@"SomeString"]
someObject.delegate = someDelegateMock;
[someObject doSomethingWhichShouldCallTheDelegate];
STAssertNoThrow([someDelegateMock verify], @"expected delegate should be called");
A workaround for this is to create an NSObject
, which implements the __weak
delegate and use some properties to verify:
Delegate Mock for weak delegate
@interface SomeDelegateMock : NSObject<SomeWeakDelegate>
@property (nonatomic, assign) BOOL someDelegateCalled;
@property (nonatomic, strong) NSString *someString;
@end
@implementation SomeDelegateMock
@synthesize someDelegateCalled = _someDelegateCalled;
@synthesize someString = _someString;
- (void) someDelegateCall:(NSString *)aString {
self.someDelegateCalled = YES;
self.someString = aString;
}
@end
Objective-c Usage of the Delegate Mock
SomeDelegateMock *someDelegateMock = [SomeDelegateMock new];
someObject.delegate = someDelegateMock;
[someObject doSomethingToCallTheDelegate];
STAssertTrue(someDelegateMock.someDelegateCalled, @"expected delegate should be called");
STAssertEqualObjects(someString, @"SomeString", @"expected delegate value");
With this workaround you can test __weak
delegates with OCMock.