iosobjective-cunit-testingocmock

OCMock: return the same value as get by parameter


I have faced with a bit specific issue while writing unit tests with the OCMock framework.

Let's say I have some method with one parameter. What I need is to stub that method and get the same value back. The value is calculated, so I can't just return some predefined value via the usual stub.

Pseudo declaration of that method (objc):

- (id)doSomething:(id)value;

Solution

  • You can use OCMock's Method Swizzling capabilities:

    @implementation OCmockPlaygroundTests
    
    - (void)testStub{
    
        TestClass * mockObject = OCMPartialMock([TestClass new]);
    
        OCMStub([mockObject doSomethingWith:OCMOCK_ANY]).andCall(self, @selector(doSomethingWith:));
        NSString * testInput = @"TEST_INPUT";
        NSString * result = [mockObject doSomethingWith:testInput];
        XCTAssertTrue([testInput isEqualToString:result]);
    }
    
    - (NSString *)doSomethingWith:(NSString *)input{
        return input;
    }
    
    @end
    

    Instead of the doSomethingWith: method of the TestClass OCMock will instead call the implementation defined in the test case which only returns the input.