It's not possible to do with your code as-is. There are two things you can do to be able to test this case - use dependency injection, or a factory method.
Option 1 - Dependency injection:
Change your method signature to require the object instead of creating it:
-(NSString *) methodWithObject:(Object*)obj
{
}
This method is preferred over option 2, but does not exactly fit the question you asked.
Option 2 - Factory method:
Instead of creating your object inline, use a helper method to return it to you:
- (NSString *) methodWithLocallyDeclaredObject{
Object *obj = [self newObject];
NSString *string1 = [obj methodOnObject];
NSString *string2 = [NSString stringWithFormat:@"prepend %@", string1];
return string2;
}
-(Object*)newObject
{
return [[Object alloc] init];
}
then you can use a partial mock to mock out the newObject
method and return something different.
id partiallyMockedObject = [OCMockObject partialMockForObject:objectToTest];
[[[partiallyMockedObject expect] andReturn:yourMock] newObject];
So you are partially mocking the object you want to test (objectToTest) to return a stubbed implementation of your locally created object