Update:
The approach below will work, but Roboguice's Events are more elegant.
I've been working through my first non-trivial Android app, and had a need for some simple messaging (Intents didn't seem like a good fit for simple, internal, app messages). I came up with the following classes.
IMessage is simply a message object whose type is identified by a string. My favorite implementation is an enum, but any class would do. Here's a simple message:
ISubscriber<T extends IMessage> describes a simple class which subscribes to a message, having its onMessage() method invoked when that message arrives. Here's a snippet of an activity and a subscriber:
IBus simply connects up the messages and subscribers, here's my simple implementation of that.
This approach works best if the IBus implementation lives outside the scope of an Activity. I've had good luck with instantiating the above Bus and injecting it where needed via Roboguice. There's probably an easier way to send simple messages around, but this is what I'm using until I find that :)
Here's the source-code for a simple test app outlining the above approach.
Monday, December 5, 2011
Wednesday, November 23, 2011
A bit of (crazy) code to manage Android fragments
Here's a bit of code I use to manage Compatibility Library Fragments in Android. Hopefully this will help someone else out.
fragmentById()
fragmentById() is doing a few odd things. <T extends Fragment> T is saying that we don't care about type-safety beyond the assurance that type T extends the Fragment class. It's worth noting that if we dropped <T extends Fragment> in favor of <T> T, then we'd lose all type safety. Here's how fragmentById() is used:The main benefits of this method are that it gets rid of a cast and it isolates the compatibility library bits off to the side (e.g. the calls to getSupportFragmentManager()).
showFragmentIds() / hideFragmentIds() / setFragmentsVisibility()
The Enum argument is an attempt at readibility, a boolean wouldn't be readable and would have the downside of limiting my ability to, say, put a 3rd visibility mode in to rip out a fragment completely. Here's what that method looks like with a boolean parameter:</rant>. The only other thing to note about setFragmentsVisibility() is the varargs parameter int... fragmentIds. This approach makes the calling code nice and simple, e.g.:As always, I welcome suggestions for accomplishing this kind of thing in a more elegant way :)
One thing to note:
The above solution works fine for trivial Fragment cases, but for more interesting things (such as specifying enter and exit animations), your best bet is to stick with the built-in fragment support.
fragmentById()
fragmentById() is doing a few odd things. <T extends Fragment> T is saying that we don't care about type-safety beyond the assurance that type T extends the Fragment class. It's worth noting that if we dropped <T extends Fragment> in favor of <T> T, then we'd lose all type safety. Here's how fragmentById() is used:The main benefits of this method are that it gets rid of a cast and it isolates the compatibility library bits off to the side (e.g. the calls to getSupportFragmentManager()).
showFragmentIds() / hideFragmentIds() / setFragmentsVisibility()
The Enum argument is an attempt at readibility, a boolean wouldn't be readable and would have the downside of limiting my ability to, say, put a 3rd visibility mode in to rip out a fragment completely. Here's what that method looks like with a boolean parameter:</rant>. The only other thing to note about setFragmentsVisibility() is the varargs parameter int... fragmentIds. This approach makes the calling code nice and simple, e.g.:As always, I welcome suggestions for accomplishing this kind of thing in a more elegant way :)
One thing to note:
The above solution works fine for trivial Fragment cases, but for more interesting things (such as specifying enter and exit animations), your best bet is to stick with the built-in fragment support.
Monday, November 21, 2011
ActionBarSherlock and RoboGuice can be friends
The ActionBar
In Android applications, the ActionBar is quickly emerging as a UI standard. Although its great, the ActionBar is only supported on Android 3.0 (API level 11, aka Honeycomb) and later. Since (either from prudence or incompetance) carriers seem to push new versions of Android out rather slowly, the majority of phones running Android are on 2x.
ActionBarSherlock and RoboGuice
There's a problem then, the ActionBar is nice, but only a small percentage of phones support it. Luckily, lots of smart folks have created ActionBar libraries for pre-3.0 Android, my favorite is ActionBarSherlock. ActionBarSherlock's API is identical to the native 3.0 ActionBar, and if the native ActionBar is available, ActionBarSherlock politely steps aside and uses it.
Another necessity, at least for me, when developing non-trivial applications is a dependency injection framework. DI frameworks are a big help, allowing me to attack large problems with a set of simple, testable, classes which collaborate but are not coupled. For Android, I'm currently using RoboGuice a popular extension of Google's Guice dependency injection framework. RoboGuice also ships with a nice set of classes easing some of the more annoying parts of developing Android apps. The problem is:
These libraries don't work in the same app
To make ActionBarSherlock work as well as it does, it includes the compatibility library and patches a few of the classes in it. A few of RoboGuice's classes such as RoboListActivity and RoboFragment extend classes from the compatibility library but not the ActionBarSherlock-patched compatibility library. The good news is that these libraries are solving different problems, and we can attack the DI side of the problem using RoboGuice and composition.
Here's a simple solution: extend the ActionBarSherlock-patched compatibility classes and get injection via composition using RoboGuice.getInjector().
You can now extend from IocListFragment (or any other class you need to create in this way such as IocFragment) and get @Inject along with a nice ActionBar:Fortunately you'll only need to extend a few classes in this way to make both of these libraries work in the same app. This solution feels a bit clunky, so if you know a better solution to this problem, please share it.
In Android applications, the ActionBar is quickly emerging as a UI standard. Although its great, the ActionBar is only supported on Android 3.0 (API level 11, aka Honeycomb) and later. Since (either from prudence or incompetance) carriers seem to push new versions of Android out rather slowly, the majority of phones running Android are on 2x.
ActionBarSherlock and RoboGuice
There's a problem then, the ActionBar is nice, but only a small percentage of phones support it. Luckily, lots of smart folks have created ActionBar libraries for pre-3.0 Android, my favorite is ActionBarSherlock. ActionBarSherlock's API is identical to the native 3.0 ActionBar, and if the native ActionBar is available, ActionBarSherlock politely steps aside and uses it.
Another necessity, at least for me, when developing non-trivial applications is a dependency injection framework. DI frameworks are a big help, allowing me to attack large problems with a set of simple, testable, classes which collaborate but are not coupled. For Android, I'm currently using RoboGuice a popular extension of Google's Guice dependency injection framework. RoboGuice also ships with a nice set of classes easing some of the more annoying parts of developing Android apps. The problem is:
These libraries don't work in the same app
To make ActionBarSherlock work as well as it does, it includes the compatibility library and patches a few of the classes in it. A few of RoboGuice's classes such as RoboListActivity and RoboFragment extend classes from the compatibility library but not the ActionBarSherlock-patched compatibility library. The good news is that these libraries are solving different problems, and we can attack the DI side of the problem using RoboGuice and composition.
Here's a simple solution: extend the ActionBarSherlock-patched compatibility classes and get injection via composition using RoboGuice.getInjector().
You can now extend from IocListFragment (or any other class you need to create in this way such as IocFragment) and get @Inject along with a nice ActionBar:Fortunately you'll only need to extend a few classes in this way to make both of these libraries work in the same app. This solution feels a bit clunky, so if you know a better solution to this problem, please share it.
Labels:
ActionBarSherlock,
RoboGuice
Friday, October 8, 2010
Dependency Injection Part 5: Mocking and Cool Tests
In my last post, we wrote a set of unit tests exercising ConsoleInputService, MessageService, and ConsoleOutputService. We tested these classes thoroughly, and in isolation since their behavior was easier to test in a controlled environment. Its now time to test our main stimulation class Magic8BallSimulator.
Remember our humble Magic8BallSimulator class? If not, here's a quick refresh:This class depends on IMessageService, IInputService, and IOutputService and those dependencies are injected via Magic8BallSimulator's constructor. Since unit testing requires a controlled environment, we'll need to make sure that the instances of IMessageService, IInputService, and IOutputService that we instantiate and inject behave in predictable ways. Remember, unit tests aim to test a simple unit of code, and for our purposes a "unit" is a method within a class.
So we have a problem
We need to make sure that the instances of IMessageService, IInputService, and IOutputService that we instantiate and inject into Magic8BallSimulator behave in predictable ways, but we want those instances to behave in different predictable ways for different tests. Consider this test:
[Test]: We want to make sure Magic8BallSimulator prints an exit message before it exits.
To get our injected instances to behave in the way we need them to for this test, we'll have to do the following:
That's too much code for us to write and maintain to test 1 case. We still have to test Magic8BallSimulator, however, after-all they pay us to write software :) The problem is, we don't want to have to write three classes to test 1 case. One way out might be to create 3 abstract classes implementing IMessageService, IInputService, and IOutputService and then extend those class only filling in the method-bodies we need for our test. That still turns out to be a ton of code to maintain, and we'd like our application to be fun to work on, not a pain in the ass. Here's a better way.
I love Moq. Check this out
We can leverage the badass, open-source, Moq library to create mock implementations of IMessageService, IInputService, and IOutputService and then use lambda expressions to stand in for the methods we want. We can then inject those mock classes into Magic8BallSimulator. Feel the lightness of the test below :)Hey, make sure you read the comments above, that's where the good explanations are! Now that we're able to use Moq to mock our dependencies, additional tests are easy! Here are 3 more:
That's it. It's been fun!
Here's the source code for this post. Thanks so much for reading these posts on Dependency Injection and Unit Testing. I had lots of fun writing these and only hope my silly examples and code-snippets were clear. If you have any questions, go ahead and leave a comment and I'll try to help you out.
Remember our humble Magic8BallSimulator class? If not, here's a quick refresh:This class depends on IMessageService, IInputService, and IOutputService and those dependencies are injected via Magic8BallSimulator's constructor. Since unit testing requires a controlled environment, we'll need to make sure that the instances of IMessageService, IInputService, and IOutputService that we instantiate and inject behave in predictable ways. Remember, unit tests aim to test a simple unit of code, and for our purposes a "unit" is a method within a class.
So we have a problem
We need to make sure that the instances of IMessageService, IInputService, and IOutputService that we instantiate and inject into Magic8BallSimulator behave in predictable ways, but we want those instances to behave in different predictable ways for different tests. Consider this test:
[Test]: We want to make sure Magic8BallSimulator prints an exit message before it exits.
To get our injected instances to behave in the way we need them to for this test, we'll have to do the following:
- Create a InputServiceStub class implementing IInputService. All the method-bodies in in this class will be empty except for ExitWasRequested() which will always return true
- Create a OutputServiceStub class implementing IOutputService. All the method-bodies in this class will also be empty empty expect for PrintExit() which will set a public PrintExitCalled property to true when called.
- Create a MessageServiceStub class implementing IMessageService with empty methods.
- Instantiate the 3 classes above. Instantiate Magic8BallSimulator and inject our 3 test instances
- call Magic8BallSimulator.Run(), and then make sure that OutputServiceStub.PrintExitCalled is true.
That's too much code for us to write and maintain to test 1 case. We still have to test Magic8BallSimulator, however, after-all they pay us to write software :) The problem is, we don't want to have to write three classes to test 1 case. One way out might be to create 3 abstract classes implementing IMessageService, IInputService, and IOutputService and then extend those class only filling in the method-bodies we need for our test. That still turns out to be a ton of code to maintain, and we'd like our application to be fun to work on, not a pain in the ass. Here's a better way.
I love Moq. Check this out
We can leverage the badass, open-source, Moq library to create mock implementations of IMessageService, IInputService, and IOutputService and then use lambda expressions to stand in for the methods we want. We can then inject those mock classes into Magic8BallSimulator. Feel the lightness of the test below :)Hey, make sure you read the comments above, that's where the good explanations are! Now that we're able to use Moq to mock our dependencies, additional tests are easy! Here are 3 more:
That's it. It's been fun!
Here's the source code for this post. Thanks so much for reading these posts on Dependency Injection and Unit Testing. I had lots of fun writing these and only hope my silly examples and code-snippets were clear. If you have any questions, go ahead and leave a comment and I'll try to help you out.
Labels:
C#,
Dependency Injection,
Introduction,
Moq,
Unit Testing
Thursday, October 7, 2010
AMF Remoting, Dependency Injection, and exposing Interfaces to Flex - FlourineFx version
In the previous post, I showed one way to wire Autofac and WebORB together to achieve AMF-Remoting as well as Dependency Injection. This post builds on the last one by providing an inplementation using Autofac and FlourineFx, the latter is a great open-source .NET AMF Remoting solution.
Here's the the source code for this post so you won't have to figure out the context of the snippets below.
Add the following to your WEB-INF\flex\services-config.xml:To tie FlourineFx to Autofac, we'll create and register our own custom Factory (we have to implement the FlourineFx's IFlexFactory interface) and instantiate our objects by resolving them from the DI Container.As in the previous example using WebORB, you now modify your Flex client to use our new destination and exposed interface like this:If there's an easier way to integrate FlourineFx and Autofac, I'd love to hear it, though the above is quite easy :)
Here's the the source code for this post so you won't have to figure out the context of the snippets below.
Add the following to your WEB-INF\flex\services-config.xml:To tie FlourineFx to Autofac, we'll create and register our own custom Factory (we have to implement the FlourineFx's IFlexFactory interface) and instantiate our objects by resolving them from the DI Container.As in the previous example using WebORB, you now modify your Flex client to use our new destination and exposed interface like this:If there's an easier way to integrate FlourineFx and Autofac, I'd love to hear it, though the above is quite easy :)
AMF Remoting, Dependency Injection, and exposing Interfaces to Flex
Imagine that we've built a large middle-tier in C# for a Flex client and have decided to remote objects to and from Flex via AMF. AMF is a great choice for us since it's a lightweight, binary, protocol which is easily de-serialized by the Flash Player (we picked the Flash Player as our client because of its current popularity).
Since our middle-tier code-base is large and complex, we've attacked that complexity by making lots of simple, loosely coupled, Single Responsibility classes. We've read about Dependency Injection and expect that if we use that general approach, we'll end up with code which is both flexible and easy to test. We'd like to avoid writing the Dependency Injection plumbing ourselves however, so we've decided to leverage Autofac to help. We've also decided to use WebORB to handle the translation of our .NET objects to Flex DTOs/VOs. Using Autofac and WebORB will allow us to focus on our business logic without concerning ourselves with translating to and from AMF and writing the necessary plumbing for Dependency Injection respectively.
We've decided to create a set of service classes which Flex can access through WebORB. Since these classes are handling client requests directly, they often depend on other injected classes to handle some of the work-load. These dependencies also keep the service classes clean, small and easy to understand. We'd also like to provide these dependent classes to our service classes through Autofac.
There are problems
We've chosen two great tools to help, but we've a few problems to work out first:
First go ahead and get the source code for this post so you won't have to cut and paste annoying code snippets.
Next we'll follow the ASP.NET Integration instructions in the all-around great Autofac wiki. After you've read the wiki entry, have a look at this simple ContainerSetup class below. This class is called by our Global.asax class to register our dependencies and help Global.asax implement IContainerProviderAccessor:
Here's the relevant section of my Global application class:The snippet above informs the classes in our application that the main application class Global is an IContainerProviderAccessor providing access to a ContainerProvider allowing callers to access the DI Container and resolve dependencies. We'll make good use of this property.
To tie WebORB to Autofac, we'll create and register our own custom Activator (we have to implement the IActivator interface, see the WebORB docs if you want to know more about Custom Activators) and instantiate our objects by resolving them from the DI Container.Configuration files
We now have to register our new DependencyActivator class in weborb.config luckily we'll only have to modify these configuration files once:Now we have to update 2 XML files which our Flex client will compile against. These files define how and where Flex will send data when remoting. First we'll create a new channel-definition in WEB-INF\flex\services-config.xml:Then we'll add a destination in WEB-INF\flex\remoting-config.xml:We now have Dependency Injection in our service classes via Autofac
Now we can finally modify our Flex client to use the new DependencyGenericDestination in its RemoteObjects. Notice that we're exposing WebORBAutofacTest.ITestService hey that's an interface!Solution benefits and drawbacks
Benefits to this approach:
Since our middle-tier code-base is large and complex, we've attacked that complexity by making lots of simple, loosely coupled, Single Responsibility classes. We've read about Dependency Injection and expect that if we use that general approach, we'll end up with code which is both flexible and easy to test. We'd like to avoid writing the Dependency Injection plumbing ourselves however, so we've decided to leverage Autofac to help. We've also decided to use WebORB to handle the translation of our .NET objects to Flex DTOs/VOs. Using Autofac and WebORB will allow us to focus on our business logic without concerning ourselves with translating to and from AMF and writing the necessary plumbing for Dependency Injection respectively.
We've decided to create a set of service classes which Flex can access through WebORB. Since these classes are handling client requests directly, they often depend on other injected classes to handle some of the work-load. These dependencies also keep the service classes clean, small and easy to understand. We'd also like to provide these dependent classes to our service classes through Autofac.
There are problems
We've chosen two great tools to help, but we've a few problems to work out first:
- Out of the box, to use our service classes in WebORB we'll need to create default constructors in them. This is unpleasant since we'd like to inject our dependent classes as constructor arguments.
- To expose our Service classes to Flex, we have 2 options:
- Expose our service classes directly to Flex, so our client can remote to, say, WebORBAutofacTest.TestService
- Create an alias which maps to each of our service classes so our client can remote to, say, AppTestService
The problem with (1) is that our Flex clients shouldn't know about the specific classes they're using on the middle-tier. This leaves us free to modify, rename, of delete those classes without the fear of breaking our client. Although this makes (2) a better option, (2) is still a bit more work because we'll have to maintain our aliases which reside in a non compiler-checked config file somewhere.
- We have no idea how to get new instances of our service classes created and their dependencies injected. In other words, we cannot get WebORB working with Autofac.
- We want to inject dependencies into our service classes as constructor arguments (and we'd like for Autofac to instantiate these dependent classes for us).
- We'd like to expose only the interfaces implemented by our service classes to our Flex client (that's a more familiar approach on the mid-tier)
- and finally, we don't want to constantly update configuration files for AMF remoting
First go ahead and get the source code for this post so you won't have to cut and paste annoying code snippets.
Next we'll follow the ASP.NET Integration instructions in the all-around great Autofac wiki. After you've read the wiki entry, have a look at this simple ContainerSetup class below. This class is called by our Global.asax class to register our dependencies and help Global.asax implement IContainerProviderAccessor:
Here's the relevant section of my Global application class:The snippet above informs the classes in our application that the main application class Global is an IContainerProviderAccessor providing access to a ContainerProvider allowing callers to access the DI Container and resolve dependencies. We'll make good use of this property.
To tie WebORB to Autofac, we'll create and register our own custom Activator (we have to implement the IActivator interface, see the WebORB docs if you want to know more about Custom Activators) and instantiate our objects by resolving them from the DI Container.Configuration files
We now have to register our new DependencyActivator class in weborb.config luckily we'll only have to modify these configuration files once:Now we have to update 2 XML files which our Flex client will compile against. These files define how and where Flex will send data when remoting. First we'll create a new channel-definition in WEB-INF\flex\services-config.xml:Then we'll add a destination in WEB-INF\flex\remoting-config.xml:We now have Dependency Injection in our service classes via Autofac
Now we can finally modify our Flex client to use the new DependencyGenericDestination in its RemoteObjects. Notice that we're exposing WebORBAutofacTest.ITestService hey that's an interface!Solution benefits and drawbacks
Benefits to this approach:
- You get a Type passed into DependencyActivator, which works nicely with Autofac's Resolve method.
- You do not have to make any modifications to your service classes for this to work (in fact your service classes do not need to depend on WebORB or Autofac at all).
- You can expose your Service classes as Interfaces.
- Instantiation of classes that don't use Autofac will be slowed down by DependencyActivator going to Autofac first. To avoid this slow-down you'll have to pick a different destination in the relevant RemoteObjects in your Flex client
Tuesday, October 5, 2010
Dependency Injection Part 4: Tests
In my last post, we identified that the SimulationRunner class violated the Single Responsibility Principle by concerning itself with:
We've arrived at code which is easy to change. That's valuable for our requirements will certainly change. There's only one rather large lingering concern:
I'm not sure it works
As our code stands now, I've no justification for believing that our application will work correctly in every circumstance. If you're sure, then you're new to this and new developers seem to know everything :) For us to be sure our code is solid, we need evidence, but why gather evidence if you're certain this application won't break? See the problem? We'll gather our evidence via a suite of simple Unit Tests.
Unit Tests
A Unit Test is a simple test of a small unit of code, for our purposes, units will be single methods. Remember our ConsoleInputService class?Here's a simple set of unit tests for ConsoleInputService. We're testing the following cases below:
As a general guideline, unit tests should be self-contained, clearly named, and as simple as possible. They should also only test one thing. This is important for when a test fails, its helpful to know exactly what broke. Have another look at the methods in ConsoleInputServiceTests above, you should be able to see what they're testing based on their names (e.g. ExitIsRequestedOnEmptyInput). Speaking of testing, here's a screen-shot of the output of the tests in ConsoleInputServiceTests, see the failure?
ExitIsRequestedOnWhitespaceInput failed. When ConsoleInputService.ExitWasRequested() encountered input that was just spaces, we expected it to return true, signalling that the user wished to exit. It evidently sees that as valid input. Let's fix ConsoleInputService.GetInput() to trim all input and re-run ConsoleInputServiceTests.We can now re-run our ConsoleInputServiceTests and we pass.
Here are a few tests of the MessageService and ConsoleOutputService classes. Here's the source code for this post as well, to run it, make sure you grab a copy of xunit, unpack it somewhere meaningful like C:\Program Files\xunit-1.6.1 then goto the Properties of the Pass4Tests project and in the Debug section set Start external program: to point to one of the xunit.console executables. Your setup should look similar to this:

Up Next
In the next post we'll tackle unit testing the Magic8BallSimulator class which is more interesting since it contains 3 dependencies.
Happy testing.
- Setting up our application, (in fact SimulationRunner created an instance of every class in the application)
- Running our application (via simulator.Run())
We've arrived at code which is easy to change. That's valuable for our requirements will certainly change. There's only one rather large lingering concern:
I'm not sure it works
As our code stands now, I've no justification for believing that our application will work correctly in every circumstance. If you're sure, then you're new to this and new developers seem to know everything :) For us to be sure our code is solid, we need evidence, but why gather evidence if you're certain this application won't break? See the problem? We'll gather our evidence via a suite of simple Unit Tests.
Unit Tests
A Unit Test is a simple test of a small unit of code, for our purposes, units will be single methods. Remember our ConsoleInputService class?Here's a simple set of unit tests for ConsoleInputService. We're testing the following cases below:
- The ConsoleInputService.GetInput() accurately returns console input
- The ConsoleInputService.ExitWasRequested() returns true when it reads a new-line from console input
- The ConsoleInputService.ExitWasRequested() returns true when it reads empty input from the console
- The ConsoleInputService.ExitWasRequested() returns true when it reads a new-line from console input
- The ConsoleInputService.ExitWasRequested() returns true when it reads a string containing only spaces from console input
As a general guideline, unit tests should be self-contained, clearly named, and as simple as possible. They should also only test one thing. This is important for when a test fails, its helpful to know exactly what broke. Have another look at the methods in ConsoleInputServiceTests above, you should be able to see what they're testing based on their names (e.g. ExitIsRequestedOnEmptyInput). Speaking of testing, here's a screen-shot of the output of the tests in ConsoleInputServiceTests, see the failure?



Up Next
In the next post we'll tackle unit testing the Magic8BallSimulator class which is more interesting since it contains 3 dependencies.
Happy testing.
Labels:
C#,
Dependency Injection,
Introduction,
Unit Testing
Subscribe to:
Posts (Atom)