My Java development and Android findings, thoughts and rants. I expect to mainly post about JDesktop and Android related issues but will no doubt go off topic many many times.

I'm writing this as someone who actually uses Java at the coal face and not as someone who sits in an ivory tower quoting happy day scenarios. So don't expect perfect code, full use of patterns. I'll be posting about stuff that is actually useful for me and with any luck others!

Core Java Books

Monday, 28 March 2011

Providing Mock API's at Runtime

This article is about how I provide a mock api's to my applications at runtime so I can test them without external services being involved.

Many of the application I work on make use of api's to servers, communications engines and so on. I find it useful to be able to test my application with mock API's so I have more control of the tests on it and can test it standalone. Also the mechanism provided allows me to run my application when a service has yet to be delivered but is defined. I could make use of dependency injection if I was to drag JEE api's into my build but I prefer the simple approach. It might not be perfect but it works.

Lets say I have an external interface that my application makes use of:

Now in my application I would typically construct a concrete class either directly or via a factory method which implements the interface contract. Whilst testing I would like to actually provide another version of the implementing class which can be used to test my application with the interface:

So what I have done is test for an alternative class being specified by a property (via the command line). If set the code attempts to construct the alternative class and use that instead of the default class usually used by the application.