Tag Archives: iOS

Stubbing a method using a completion block in an iOS Kiwi test case

Kiwi is a great BDD (Behaviour-driven development) testing framework for iOS. The structure of a Kiwi test case involves specifying expected outcomes and behaviours for a given context or situation. The emphasis is on testing the “what” not the “how”.

I’ve been using Kiwi a fair bit recently, when I ran into a situation I wanted to test that wasn’t as clearly documented as I would’ve liked, so I thought I’d provide the solution I used here. I felt it best to dive straight into some example code to better explain the situation:

Class being tested: ClientOfApiService

Method being tested: doSomeActionThatInvolvesApiService:

Class dependencies: ApiService

To properly test the behaviour of ClientOfApiService in isolation, we need to provide a mock of the dependency ApiService; failing to do this would mean relying on external behaviour which could potentially lead to inconsistent/invalid results.

ClientOfApiService.h

typedef void(^ActionCompletionBlock)(BOOL success);

@class ApiService;

@interface ClientOfApiService : NSObject

@property(strong, nonatomic) ApiService *apiService;

/*
 * Performs some action that requires the result of an API to indicate
 * success or failure.
 */
-(void) doSomeActionThatInvolvesApiService:(ActionCompletionBlock) completion;

ClientOfApiService.m

-(void) doSomeActionThatInvolvesApiService:(ActionCompletionBlock) completion;
{
    [self.apiService fetchTestNames:^(NSArray *testNames, NSError *error) {

        if (error)
        {
            completion(NO);
            return;
        }

        // Success is arbitrarily a name array of size 2
        BOOL success = (testNames != nil && [testNames count] == 2);

        completion(success);
    }];
}

ApiService.h

typedef void(^TestNamesCompletionBlock)(NSArray *testNames, NSError *error);

@interface ApiService : NSObject

/*
 * Fetches some test names from the API and calls the specified completion
 * block when a result is received.
 */
-(void) fetchTestNames:(TestNamesCompletionBlock) completion;

So, the objectives are:

  1. Stub the fetchTestNames method to use dummy data so that it does not have to make a real API call.
  2. On top of stubbing the fetchTestNames method call, we want the method to capture the TestNamesCompletionBlock parameter so that it can properly call back by executing the block with the dummy data.
  3. In our test case, verify that the outcome of the doSomeActionThatInvolvesApiService method is correct given the stubbed data used.

I’ll end this post with an example of a Kiwi test case that achieves the above objectives:

#import <Kiwi/Kiwi.h>
#import "ClientOfApiService.h"
#import "ApiService.h"

SPEC_BEGIN(ClientOfApiServiceSpec)

describe(@"ClientOfApiService", ^{
    
    // system under test (class being tested)
    __block ClientOfApiService *sut;
    __block id apiService;
    
    // Runs before each test
    beforeEach(^{
        sut = [[ClientOfApiService alloc] init];
        apiService = [KWMock mockForClass:[ApiService class]];
        
        // Inject the mocked apiService into the ClientOfApiService instance
        sut.apiService = apiService;
    });
    
    // Runs after each test
    afterEach(^{
        sut = nil;
        apiService = nil;
    });
    
    it(@"ClientOfApiService instance should exist", ^{
        [sut shouldNotBeNil];
    });
    
    // Given a particular context
    context(@"When testing doSomeActionThatInvolvesApiService with some dummy data", ^{
        
        // Runs before each test
        beforeEach(^{
            
            // OBJECTIVE 1. Stub the mocked ApiService to return an array of 2 names
            // We stub using a block so that we can capture that parameters passed to the
            // method we are stubbing. The parameters can be accessed in the params array
            // object
            [apiService stub:@selector(fetchTestNames:) withBlock:^id(NSArray *params) {
                
                // OBJECTIVE 2. Capture the TestNamesCompletionBlock parameter passed in so
                // that we can call back with the dummy data. The completion block parameter
                // is the only parameter of the method, so we access it at index 0.
                TestNamesCompletionBlock completionBlock = [params objectAtIndex:0];
                
                // Dummy data with 2 names
                NSArray *dummyArray = [NSArray arrayWithObjects:@"John", @"Matt", nil];
                
                // call back by executing the completion block parameter
                completionBlock(dummyArray, nil);
                
                // the test framework requires the block to return something
                return nil;
            }];
            
        });
        
        // Verify that some condition is met. For test purposes,
        // success is abitrarily defined as the ApiService returning
        // exactly 2 names.
        it(@"should result in success being returned", ^{
            [sut doSomeActionThatInvolvesApiService:^(BOOL success) {
                
                // OBJECTIVE 3. verify that the correct result was returned
                // given the dummy data used.
                [[theValue(success) should] equal:theValue(YES)];
            }];
        });
        
    });
});

SPEC_END
Advertisements

Authenticated Google Cloud Endpoint call from an iOS client

In my last post I mentioned the Google Cloud Endpoint framework which is a great way to produce an API that can be consumed across multiple platforms. Even though it is in preview release and subject to some teething problems, I highly recommend checking it out.

In a nutshell, the framework allows you to develop a backend and then generates the necessary data and proxy classes to use in your client projects to talk to the API. This means you no longer have to be concerned with the mechanics of making an API call, parsing the response data, etc., but can interface with the entire API through objects.

I’ve been playing around with the framework in bits and pieces and recently explored making an authenticated API call from an iOS client when I discovered a rather annoying issue: after successfully authenticating a user with OAuth 2, the local dev server would reject any subsequent API calls with the following error:

Cannot authorize request with scheme http

My iOS simulator and local dev server were just not getting along….

I knew that the problem was my local dev server was plain old http and that something, somewhere required https. After several attempts and the lack of any obvious info online, I started digging around the source code of the generated client classes…and, bingo!

The problem turned out to be that the iOS OAuth2 library would not authorize non-https requests, which meant I could not test authenticated calls locally. I eventually found a flag in the GTMOAuth2Authentication class of the iOS OAuth2 library which allows the library to authorize all requests (including non-https):

// Property indicating if this object will authorize plain http request
// (as well as any non-https requests.) Default is NO, only requests with the
// scheme https are authorized, since security may be compromised if tokens
// are sent over the wire using an unencrypted protocol like http.
@property (assign) BOOL shouldAuthorizeAllRequests;

By default this flag is set to NO. To update this flag to work with my outgoing requests, I changed its value in the OAUTH callback method prior to making any API requests:

- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuth2Authentication *)auth
                 error:(NSError *)error {
    [self dismissViewControllerAnimated:YES completion:nil];

    if (error != nil) {
        // Authentication failed
        ...
    } else {
        // Authentication succeeded
        ...

        // TODO: for development purposes only to use non-https....remove for release.
        auth.shouldAuthorizeAllRequests = YES;

        // Make some API calls
        ...
    }
}

Ta-da.

The iOS BlocksKit framework is awesome…

iOS Blocks are segments of code that can be passed around for later execution, in the same manner as a value or parameter can be passed to a function. At first, the syntax surrounding the use of blocks may seem a little confusing or unconventional, but once you begin to use them, you will find that they are in fact relatively straightforward and can speed up your development in many instances.

void (^simpleBlock)(void) = ^{ ..... eh??!!?

void (^simpleBlock)(void) = ^{ ….. eh?!!?

The really great thing about Blocks is that they give you a quick way to define a snippet of code that can capture and access the enclosing scope and its values, yet still be executed at later point in time when a particular event has occurred; all of this without the hassle of having to define excessive delegates or callbacks.

BlocksKit is a really neat framework which consists of lots of utility and category classes to make the use of blocks more accessible with existing framework classes such as NSDictionary and UIBarButtonItem. Below is just one example of where BlocksKit can come in handy.

Example: Presenting a ModalViewController

Let’s take the example of presenting an information screen (InfoViewController) to a user in a universal application. On an iPad we may want to present the information screen as a popover without a navigation bar, however, on an iPhone we may want to present the screen modally but provide the user with a ‘Done’ bar button in the navigation bar to dismiss the screen; furthermore, let’s say we wanted to do this without having to alter the .xib of the InfoViewController.

One method of doing this would be to modify the InfoViewController’s implementation to add a ‘Done’ button only if executed on an iPhone, such as:

- (void)viewDidLoad
{
    [super viewDidLoad];

    BOOL iPhone = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone);

    if (iPhone)
    {
        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissViewController:)];
        self.navigationItem.rightBarButtonItem = doneButton;
    }

    ...
}

This would result in a dismiss ‘Done’ button appearing in the navigation bar on an iPhone, but not when running on an iPad. Whilst this works, in some cases it’s not ideal that the InfoViewController itself has to be aware of how it is being presented, i.e. modally in this case; one would rather leave such logic to whatever is creating and using the view controller. Another (better) option would be to have the creator/user of the InfoViewController simply assign the navigation bar button itself and implement the button’s callback (selector) methods to dismiss the view controller. The downside here is having to implement unnecessary callback methods which clutter your class for such a simple purpose.

This is where blocks can come in really handy. For little tasks such as these, blocks containing the necessary operations to execute at a later stage can be defined and assigned in one place where it makes sense. Below is one example of how the above exercise can be implemented using BlocksKit:

    BOOL iPhone = ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone);

    InfoViewController *infoVC = [self.storyboard instantiateViewControllerWithIdentifier:@"InfoViewController"];

    if (iPhone)
    {
        UINavigationController *modalController = [[UINavigationController alloc] initWithRootViewController:infoVC];

        // Present the view controller modally
        [self presentViewController:modalController animated:YES completion:^{

            // This block gets executed once the info view controller has finished presenting.

            // Create the done button for the navigation bar and implement the block that gets
            // executed when the button is tapped.
            UIBarButtonItem *doneBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone handler:^(id sender) {

                // When the button is tapped, dismiss the view controller
                [modalController dismissViewControllerAnimated:YES completion:nil];
            }];

            [infoVC.navigationItem setRightBarButtonItem:doneBarButton animated:YES];
        }];
    }
    else
    {
        // Show as a popover view controller
    }

And that’s it! Make sure to check out the BlocksKit framework for many useful classes that can make simple tasks quicker and cleaner IMO.

Simple Data Cache for iOS

I was searching for a simple cache to use for temporary storage of data from web-service calls when I came across EGOCache. Essentially I wanted something that provided the following features:

  • Simple key/value storage structure.
  • Time expiration of data.
  • Persistence of data in the cache.
  • Ability to easily store and persist custom objects.

So far EGOCache has worked really well for my purposes, and storing a custom object is as easy as implementing the NSCoding protocol on your object. The cache also provides an easy access mechanism to the global cache through the following call:

[EGOCache globalCache]

Although I recommend using the cache through a wrapper class; it will prevent coupling your code to the implementation and will safeguard your application code from changes to a different caching mechanism.

UIRefreshControl bug in landscape mode.

The iOS UIRefreshControl provides a standard “pull-down-to-refresh” mechanism for certain UIScrollView classes such as UITableView and UICollectionView.

The UIRefreshControl, however, has a bug in landscape mode on the iPhone whereby there isn’t enough room to pull down to trigger the refresh mechanism. Go here for more information on the bug and possible workarounds.

I ended up using the following code in my UIScrollViewDelegate implementation (both UITableViewDelegate and UICollectionViewDelegate conform to UIScrollViewDelegate):

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.collectionView.contentOffset.y < -80 && ![self.pullDownRefreshControl isRefreshing])
    {
        [self.pullDownRefreshControl beginRefreshing];
        // perform refresh operation...
    }
}

The “pull-down-to-refresh” animation isn’t as slick, but it’s a good workaround for now.

Using CocoaPods with an iOS static library

Static Libraries

When developing different iOS projects, you will most likely want to keep common code in a shared library that each individual project can make use of. A useful way of doing this is to package your shared code as a static library which can then be imported into each application project. One problem I had previously experienced when building my own static library a long time ago was the difficulty in bundling resources such as nib files within the library. I wanted to be able to share common code, but what good was it if the library wasn’t going to include all the bits and pieces I wanted, right?!

ponder

Fortunately, there is a great post available here which describes exactly how one can go about building a static library with resources for iOS. I’ve followed the process myself and it works really well. Once setup is complete, as part of building your project it will also build your library and link your project object files against the static library.

Some things to take note of:

  • When performing step 7 (Linking with the Library) of the static library process is to ensure that your library xcode project is closed when attempting to drag the library project from finder into your project navigation pane, otherwise it may not import correctly.
  • When adding new files to your static library, ensure that the header files are added to the Copy Files build phase of your target.

CocoaPods

CocoaPods is a neat tool for managing library dependencies in an Objective-C project. Just like Apache Maven, CocoaPods allows one to specify dependencies in a configuration file and will automatically fetch, install and configure the project with those dependencies.

When using a static library and CocoaPods with your iOS projects, it may be the case that your application project and static library make use of the same 3rd party external libraries. You may think to yourself that you will setup your CocoaPods configuration so that only your static library project includes the 3rd party libraries, in hopes that these will automatically be linked in when building your main project against your static library, however, this won’t work given the way CocoaPods structures your workspace. A static library is essentially just an archive of object files that ultimately get linked to create a final binary/application, so you need to explicitly include the 3rd party libraries in your application project for the linking to take place at build time.

Below are high-level steps to setup a workspace whereby a static library and application project make use of the same 3rd party library, for instance the AFNetworking library:

  • Create a static library project LibProject as shown above.
  • In the root folder of LibProject, create a CocoaPods configuration file Podfile with the following contents:

platform :ios, ‘6.0’

pod ‘AFNetworking’, ‘1.0’

  • Using the terminal, execute the command ‘pod install‘ in the root folder of LibProject.
  • Import the static library project LibProject into your main application project AppProject as explained in the first section of this post.
  • In the root folder of Approject, create a CocoaPods configuration file Podfile with the same contents as above.
  • Using the terminal, execute the command ‘pod install‘ in the root folder of Approject.
  • Make sure to open your project using  AppProject.xcworkspace instead of AppProject.xcodeproj.
  • Hopefully your project can now make use of AFNetworking and build correctly 🙂

CocoaPods Tip: whenever using ‘pod install‘ to setup your Cocoapods dependencies for a project, make sure not to use the superuser, i.e. ‘sudo pod install‘… this will lead to nasty permission problems later on!

Is there finally apostasy amongst the fanboys?

I’ve had an interest in mobile for a long time and I’ve also had the privilege of being involved in the mobile dev scene for quite some time. This is a scene that is currently dominated by two platforms: Apple iOS and Google Android.

I must admit, until recently, when it had come to picking sides I had been very wishy washy; I had always taken a liking to Android, it was geeky and something about the community and the Google machine had me believing it would turn out to be big. Having said that, iOS had always seemed so slick and generally superior from an app and ecosystem point of view. My position was weak, I’d smack-talk the fanboys but deep down I couldn’t deny the superiority of the Apple products.

Things change. A good friend of mine pointed me to an article written by a self-proclaimed fanboy in which he describes his experience of switching to Android:

http://www.rottmann.net/2013/01/an-iphone-lovers-confession-i-switched-to-the-nexus-4-completely/

This is an interesting read and I’ve since followed Ralf on Google+ and subscribed to his site feed. What I found most interesting about the article is the frustration Ralf presents when discussing sharing and task-switching on iOS after having used Jelly Bean on Android… sentiments I agree with completely since having my Galaxy Nexus and subsequently using an iPhone (generally for testing purposes). Check out the article, it’s worth a read for anyone interested in the mobile space.