OCMockito – How to handle returning NSError

Leave a comment

I find mocking pointers (specifically NSError’s) a bit of a pain in OCMockito. But here is a way I get things working if I just want to set an expectation, and have it return NULL.

Handler.h

@interface Handler : NSObject
- (BOOL)playTrack:(NSString *)track error:(NSError **)errorPtr;
@end

PlayerTest.m

#import <XCTest/XCTest.h>

#import <OCHamcrestIOS/OCHamcrestIOS.h>
#import <OCMockitoIOS/OCMockitoIOS.h>

#import "Player.h"

@interface PlayerTest : XCTestCase
@property (nonatomic, strong) Player *player;
@property (nonatomic, strong) Handler *mockHandler;
@end

@implementation PlayerTest

- (void)setUp {
    [super setUp];
    self.mockHandler = mock([Handler class]);

    self.player = [[Player alloc] initWithHandler:self.mockHandler];
}

- (void)testPlayTrack {

    // given
    [[given([self.mockHandler playTrack:anything() error:NULL]) withMatcher:anything() forArgument:1] willReturnBool:YES];

    // when
    [self.player playURL:@"spotify.track.xxx" error:NULL];

    // then
    [verify(self.mockHandler) playTrack:anything() error:NULL];
}

How setup OCMockito XCode 7

Leave a comment

This was actually pretty easy. Go to this web site

https://github.com/jonreid/OCMockito

Download the zip releases from each of these frameworks

https://github.com/jonreid/OCMockito/releases/
https://github.com/hamcrest/OCHamcrest/releases/

Expand them and drag in the iOS framework into your project.

Screen Shot 2015-10-01 at 8.28.56 AM

Note: When you drag libraries in, you want the libraries, not the source code.

Screen Shot 2015-11-13 at 10.19.47 AM

Screen Shot 2015-11-13 at 10.19.57 AM

And when you drag them in, make sure you add them to the Test Group

Screen Shot 2016-04-05 at 9.15.18 AM.png

So it should look like this.

Screen Shot 2015-11-13 at 10.21.36 AM

And then set the ‘Other linker flags’ by double clicking on your blue project icon.

Screen Shot 2015-10-01 at 8.29.55 AM

Note: Flip to your test project target, as this is where we want to add our linker flags.Screen Shot 2016-09-11 at 2.39.50 PM.png

Then goto ‘Build Settings’ and type ‘Other linker flags’ in the search box and add ‘-ObjC’ to both the debug and release.

Screen Shot 2015-10-01 at 8.31.03 AM

If you don’t set the -ObjC correctly you will see this

Screen Shot 2017-04-12 at 10.38.12 AM.png

Note: Make sure you get the LATEST libraries.

%d bloggers like this: