I'm getting used to OCMock. Coming from a Java/JMock background I'm now looking for the ability to say [[[myMock stub] returnValueFromCustomMethod] someMockedMethod]; where returnValueFromCustomMethod is defined in the test class. I was originally thinking something along the terms of [[[myMock stub] usingSelector:@selector(myMethod:)] someMockedMethod]; but after writing I wonder if my first approach makes more sense. Either way, could someone show me if and how this can be done?
A:
That's pretty close to what I'm looking for! Stil there's a lot of noise in the code. I tried a mix of your suggestion along with another approach but I seem to be off by one.
@interface OCMockRecorder (CustomMethods)
- (id) andPerformsSelector:(SEL)selector onTargetObject:(id)targetObject;
@end
@implementation OCMockRecorder (CustomMethods)
- (id) andPerformsSelector:(SEL)selector onTargetObject:(id)targetObject
{
NSMethodSignature *signature = [[targetObject class] instanceMethodSignatureForSelector:selector];
// set up an invocation equivalent to [self customMethod]
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setTarget:targetObject];
[invocation setSelector:selector];
// introduce it into the mock
[self setUpReturnValue:invocation];
return nil;
}
@end
Then to test I use:
@interface OCMockExtensionsTest : SenTestCase
{
BOOL methodWasCalled;
}
-(void) willBeCalledOnBehalfOfMock;
@end
@implementation OCMockExtensionsTest
-(void) willBeCalledOnBehalfOfMock
{
methodWasCalled = YES;
}
-(void) setUp
{
methodWasCalled = NO;
}
-(void) testOCMockExtensions
{
NSString* aMock = [OCMockObject mockForClass:[NSString class]];
[[ [(id)aMock stub] andPerformsSelector:@selector(willBeCalledOnBehalfOfMock) onTargetObject:self]
initWithString:OCMOCK_ANY];
STAssertFalse(methodWasCalled, @"Method should not be called until after the mocked method is invoked.");
[aMock initWithString:@"Hello World!"];
STAssertTrue(methodWasCalled, @"Method SHOULD be called after the mocked method is invoked.");
}
@end
Yet I see the error: error: OCMockObject[NSString]: unexpected method invoked: initWithString:@"Hello World!" stubbed: (null) Which tells me my invocation isn't being matched.
Cliff
2009-01-28 02:20:07
A:
Dominic Cooney
2009-02-06 00:08:21