Question

I have been using OCMock to create stub and mocks. I'm struggling to mock a locally declared objects method though.

If I have the code below:

// Example.m 
#import "Object.h"

- (NSString *) methodWithLocallyDeclaredObject{

    Object *obj = [[Object alloc] init];
    NSString *string1 = [obj methodOnObject];
    NSString *string2 = [NSString stringWithFormat:@"prepend %@", string1];

    return string2;

}

I want to be able to stub out the call to methodOnObject as it interacts with the filesystem and just return a string. How would I do this?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top