Tag Archives: Frameworks

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.

Tidbits

Just some interesting bits and pieces I have come across recently:

Flat UI Colors: a neat website that displays a colour palette, allowing you to click on a colour to copy its value to the clipboard. #design

ColorHex #android App: a simple colour picking app that that also allows one to store favourite colours. #design

Butter Knife: an interesting view injection framework for #android, created by Jake Wharton who also developed the ActionbarSherlock framework.

Latest Android Dashboard Stats: personally, I was surprised to see that as much as 9.9% of devices still fall under the small, ldpi configuration. #android


#programming #object-orientation

I recently did a bit of a refresh on some principles and guidelines for object orientated programming:


#server-side

I spent a bit of time recently developing a simple REST web-service using Google go and Google App Engine. Here are some useful links and examples:

  • Gorca: a utility package for RESTful go applications on App Engine.
  • Home: a simple App Engine application using go and Angular JS.
  • RESTful web-services in go: useful information on developing RESTful web-services using Google go.

Anyone interested in developing web-service APIs that need to be consumed by mobile apps and the web, should definitely have a look at Google Cloud Endpoints… I also played around with this cool feature for Java and below are some useful links:

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.

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!

Otto Event Bus for Android

In case you haven’t already checked out this cool framework, Otto is an event bus designed to help parts of your application communicate more effectively and in a more decoupled manner.

With respect to Android, one particular area where the Otto event bus can be really useful is in the passing of complex data objects between the Activity andFragment objects in your application. For instance, when passing a data object between two fragments, traditional methods relied on passing the object via the parent activity or by using the setTargetFragment()/getTargetFragment() methods of the Fragment class; a downside to these approaches is that it couples your fragments/activities to one another. Whilst one can use Interfaces to alleviate the coupling, it requires additional boilerplate code and if more than a single object is required one can be faced with handling the code and coupling of many Interfaces, which is often excessive. The following is a simple Java example of how Otto can simplify the communication amongst components and reduce coupling and boilerplate code.

We have a weather service which periodically needs to provide weather updates to various components. Without the use of Otto, the following is an example of how this could be achieved:

WeatherService Class

 public class WeatherService
{
	private String weatherDescription;
	private List<WeatherListener> listeners = new ArrayList<WeatherListener>();

	
	public void weatherHasBeenUpdatedFromSomewhere(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		if (listeners != null)
		{
			for (WeatherListener listener : listeners)
			{
				listener.weatherUpdated(weatherDescription);
			}
		}
	}
	
	public void addListener(WeatherListener listener)
	{
		listeners.add(listener);
	}
}

This class has to maintain a list of listeners which it publishes updates to. Notice that although it isn’t coupled with any concrete class, it still has to know about an interface which does very little. Also notice how a large amount of the code is concerned with managing the listeners.
 
WeatherListener Interface


public interface WeatherListener
{
	public void weatherUpdated(String weatherDescription);
}

A simple listener interface. This is largely just boilerplate code given how little this interface achieves.
 
WeatherScreen Class


public class WeatherScreen implements WeatherListener, SomeOtherRandomService
{
	private String weatherDescription;

	@Override
	public void weatherUpdated(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		// Do something...
	}

	@Override
	public void randomAction(RandomObject randomObject)
	{
		// Do something...
	}
}

Nothing fancy here, the WeatherScreen class listens for weather updates and possibly information from other services. One can easily see how it’s possible for these publisher/listener connections to result in a lot of unnecessary coupling and boilerplate code.

If we take the same example and use the Otto event bus to manage a lot of these connections, we end up with something like the following:

OttoWeatherService Class

public class OttoWeatherService
{
	private String weatherDescription;
	private Bus eventBus;
	
	public OttoWeatherService(Bus eventBus)
	{
		this.eventBus = eventBus;
		eventBus.register(this);
	}
	
	public void weatherHasBeenUpdatedFromSomewhere(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		// post the updated weather on the event bus.
		eventBus.post(weatherDescription);
	}
	
	@Produce
	public String produceWeatherUpdate()
	{
		return weatherDescription;
	}
}

When the OttoWeatherService class receives an update, it posts an event on the bus to notify all subscribers. Note that the service class now has less responsibility as it no longer needs to be concerned with a list of listeners and is immediately decoupled from the interface. Also note that this class is a Producer, meaning that as soon as an interested subscriber registers on the bus it will receive the latest update.

OttoWeatherScreen Class

public class OttoWeatherScreen
{
	private String weatherDescription;
	private Bus eventBus;
	
	public OttoWeatherScreen(Bus eventBus)
	{
		this.eventBus = eventBus;
		eventBus.register(this);
	}
	
	@Subscribe
	public void weatherAvailable(String weatherDescription)
	{
		this.weatherDescription = weatherDescription;
		
		// Do something...
	}
	
	@Subscribe
	public void randomObjectAvailable(RandomObject randomObject)
	{
		// Do something...
	}
}

The WeatherScreen class now receives updates from the various services by subscribing for these updates/events on the bus. Otto results in less classes having to be created and less code concerned with connecting your components up, allowing the existing classes to focus on performing core functions.

The above was just one example of how Otto can reduce the complexity surrounding communications/connections in your application. Coupling is reduced but strongly typed event production/subscription is still maintained.
 
I’ve created an OttoSample Android project on GitHub that provides a simple demonstration of how the Otto event bus can be used to communicate an object between two fragments. Please note that this project also makes use of the Android Annotations framework for object/view dependency injection; I plan to discuss and provide feedback on this framework in the near future.