OCMock test code with intermediate variable

144 views Asked by At

I am new to using OCMock. I have the following simplified code I want to test -

@implementation ViewController

- (void)presentSomething:(NSString *)string {
    NSLog(@"doSomethingElseWithString - %@", string);
}

- (BOOL)handleResult:(NSString *)result
{
    BOOL handled = YES;
    NSString *changedString = [result uppercaseString];
    [self presentSomething:changedString];
    return handled;
}

@end

and I have a test as follows

- (void)testExample {
    ViewController *vc = [ViewController new];
    id mockViewController  = OCMPartialMock(vc);
    OCMStub([mockViewController presentSomething:@"1234"]);

    BOOL handled = [vc handleResult:@"1234"];
    XCTAssertTrue(handled);

    OCMVerify([mockViewController presentSomething:@"1234"]);
}

I want to verify presentSomething gets called with the correct argument after I call handleResult.

The test either gives a EXC_BAD_ACCESS while verifying or fails saying the presentSomething method was not invoked.

If I change the handleResult method as follows the test runs and passes.

- (BOOL)handleResult:(NSString *)result
{
    BOOL handled = YES;
    [self presentSomething:result];
    return handled;
}

It seems that intermediate [result uppercaseString] and variable caused the issue. Is this an issue with how I am using OCMock or a bug in OCMock?

1

There are 1 answers

0
Ben Flynn On

Must be trying to do a pointer comparison instead of isEquals. I haven't tried debugging the issue against the source code yet, but there is a workaround:

- (void)testExample
{
    ViewController *vc = [ViewController new];
    id mockViewController  = OCMPartialMock(vc);
    OCMExpect([mockViewController presentSomething:@"1234"]);    
    BOOL handled = [vc handleResult:@"1234"];
    XCTAssertTrue(handled);    
    OCMVerifyAll(mockViewController);
}