Principal Consultant @ Thoughtworks
Erik Doernenburg is a Principal Consultant at ThoughtWorks Inc. where he is helping clients with the design and implementation of large-scale enterprise solutions. Building on his experience with J2EE, Microsoft .NET and other environments, Erik is continually exploring patterns of enterprise software. He is an advocate of agile development and Open Source software, holds a degree in Informatics from the University of Dortmund and has studied Computer Science and Linguistics at the University College DublinPresentations by Erik Doernenburg
Test Driven Development, Take 2
More and more developers are being drawn to Test Driven Development (TDD). It doesn?t take much time or effort to get going, especially after you have passed that first hurdle of approaching development using the mantra of ?red-green-refactor? instead of ?code for days and then debug and test?. But after a while you discover that TDD has more to it than just basic state-based testing. "erik doernenburg
Tuesday, August 12, 2008
The Spring framework has become ubiquitous in the Java world, and there are a large number of tools supporting developers of Spring-based applications. In this post I describe SpringViz; or, more accurately, my variant of it.
SpringViz helps developers with what is at the heart of a Spring-based application, the container and the contexts files that describe the beans. In larger projects these context files can grow quite a bit. Newer versions of the Spring framework introduced features that help reduce the clutter and there are vast numbers of blog posts voicing different opinions on what should and what shouldn’t be in a context file but, no matter what, the number of beans in the context files will grow with the size of a project, and at some point it becomes difficult to understand the overall structure. This is no different from trying to maintain an understanding of a large codebase. In fact, I consider the context files to be code rather than configuration.
I’ve argued before (here and here for example) that to deal with the complexity and sheer size of software systems we need a 1000ft view. This is a view that uses visualisation techniques to aggregate large amounts of data and multiple metrics into one big picture. SpringViz provides that 1000ft view for Spring context files.
Let’s look at an example first. The following diagram shows the context files for the Spring JPetStore example application (click on the image for the full-size version):
I find that this diagram presents the architecture of the application quite nicely. The web controllers are defined in the petstore-servlet context in the top left and many of them have a dependency on the petStore bean, defined in the main application context. The petStore bean in turn has dependencies on all the DAOs, which are defined in the data access context. In that context we can clearly see how the top four DAOs share the same data source while the Order and Sequence DAOs use a different one. In addition to the individual dependencies we also get an impression of the overall architecture: a simple, multi-layered design with a single central choke point that acts as an adaptor between the presentation and data access layers.
From personal experience I can say that the bigger and more complex a system gets, the more valuable these diagrams become. In many cases they not only help share a common understanding of the architecture in the development team but they also help spot inconsistencies in the design and often trigger and support discussions around important restructurings. Ok, this is all I’m going to say to convince you to try out SpringViz. In the following paragraphs I’ll explain how to use it on your own projects.
Step 1: You need a copy of SpringViz. The version I’m discussing in this article can be downloaded here. When you unzip the archive you should have an Ant build file, a springviz folder with a few files in it and an example folder that contains the context files for JPetStore.
Step 1b: SpringViz uses GraphViz Dot to render the diagram. So, if you don’t have this on your system you need to download and install it. You should also open the build file and change the dot.command property to point to the Dot executable. On the Mac you should really get Pixelglow’s version of GraphViz.
Step 2: You can now run SpringViz by calling Ant with the default target. This will create a target folder, process the context files with the SpringViz XSLT sheet to create an input file for GraphViz Dot, and then invoke Dot to create beans.png, the final diagram.
Step 3: To integrate SpringViz into your own projects you can simply add the contents of the build file to your build file, place the springviz folder in an appropriate place, and adjust the configuration properties at the top of the build file.
If you are adventurous you can have a look at the Dot documentation and change the XSLT sheet to create slightly different input for Dot. You could colour the beans according to all sorts of criteria or you could change other aspects of their appearance depending on bean attributes.
There are a few limitations that you should be aware of: In its current version the system can’t deal with multiple beans with the same name defined in different contexts. So, if you have a defaultUrlMapping bean or similar in multiple files and you have dependencies to/from these the resulting diagram will be wrong. In this case it’s easiest to modify the style sheet to filter out the problematic beans. Another important point is that in its current form the sheet simply tries to use a bean’s id and name, which usually works out but will cause problems when beans have both, name and id. And lastly, the XSLT processor will need access to the web to fetch the schema files. I guess this can be avoided but so far this hasn’t been a problem for me.
If you missed the link above you can download the specific version of SpringViz discussed in this article from this site. The latest version of SpringViz as well as more documentation and resources are available on Mike Thomas’s site.
Thursday, July 3, 2008
For a few releases the Apple development tools have included OCUnit and many developers have now started to write unit tests. There are lots of tutorials that explain how this is done for the straight-forward cases but there’s one area of testing that has proven difficult on most platforms, and that is testing of the user interface. That said, there are a few things that make this an easier problem to solve with Cocoa and in this post I’ll explain why.
Let’s look at an example. CCMenu is a small application that displays the status of CruiseControl continuous integration servers. As part of adding a new project to be monitored the user has to enter the URL for the CruiseControl server and a combox provides a history of previously used servers.
The same dialog has a matrix of buttons to set the type of the server. Actually, by default CCMenu detects the server type automatically but that’s beside the point. What we’re interested in is the piece of functionality that is responsible for selecting the correct server type for the URL chosen by the user. In our case, this would be Cruise Control Dashboard.
One difference between Cocoa and most other UI frameworks is the fact that the user interface is stored by serialising the objects, rather than generating code. For this reason I’m happy to not insist on test-first for the actual interface. What I do want to test is the code in the controller classes.
Obviously, I could load the serialised objects, locate the elements involved and then use methods such as performClick: to trigger the actions. Sounds convoluted? Yes, I agree. Luckily there’s a better way.
This is a case where testing is tricky because the object under test interacts with objects that are difficult to deal with. In such cases dynamic mock objects have proven extremely useful. A good introduction can be found here and mockobject.com lists papers and implementations. For Objective-C I created OCMock. Let’s look at how this helps us testing our controllers.
Here are the relevant parts of the interface declaration of the controller. Given that I’m doing test-driven development there’s currently no implementation of the methods. I simply created the interface of the controller based on my needs while designing the dialog.
@interface CCMPreferencesController : CCMWindowController
{
IBOutlet NSComboBox *serverUrlComboBox;
IBOutlet NSMatrix *serverTypeMatrix;
}
- (IBAction)historyURLSelected:(id)sender;
In my test I want to use mock objects instead of loading the actual user interface. So, in the test setup, after creating my controller, I create appropriate mock objects and set up the controller to use these.
@implementation CCMPreferencesControllerTest
- (void)setUp
{
controller = [[[CCMPreferencesController alloc] init] autorelease];
serverUrlComboBoxMock = [OCMockObject mockForClass:[NSComboBox class]];
[controller setValue:serverUrlComboBoxMock forKey:@"serverUrlComboBox"];
serverTypeMatrixMock = [OCMockObject mockForClass:[NSMatrix class]];
[controller setValue:serverTypeMatrixMock forKey:@"serverTypeMatrix"];
}
You notice that I’m using key-value coding to set the variables (outlets). I’m doing this because the variables are not public and at the same time I don’t want to write accessor methods for them.
Now, we can start writing the actual test for the functionality. Have a look at the full test first.
- (void)testSelectsServerTypeWhenHistoryURLIsSelected
{
NSString *selectedUrl = @"http://localhost/cctray.xml";
[[[serverUrlComboBoxMock stub] andReturn:selectedUrl] stringValue];
[[serverTypeMatrixMock expect] selectCellWithTag:CCMCruiseControlDashboard];
[controller historyURLSelected:nil];
}
What’s going on here? Firstly, I tell the mock object that stands in for the actual combox box that it should stub the stringValue method. This means that when somebody invokes stringValue on this object it will return the string @”http://localhost/cctray.xml”. This is all we’d have done with the real combo box anyway.
Secondly, I tell the mock that stands in for the server type matrix that it should expect that the method selectCellWithTag: is called with CCMCruiseControlDashboard as an argument.
Lastly, I invoke the method I want to test. What happens, once the implementation is complete, is that the code will go the the combo box and ask it for its string value. The first mock will return the stubbed value. Now, the code should do whatever it needs to do to figure out which server type this corresponds to and then set that in the server type matrix by selecting the cell with the appropriate tag, and this is what we’ve told the second mock to expect.
Wait, you might say, we don’t have an implementation yet. So, how does this test fail? It doesn’t yet. We’ll have to tell the mock objects to verify that everything we told them to expect actually occurred, and a logical place for this is the test tearDown.
- (void)tearDown
{
[serverUrlComboBoxMock verify];
[serverTypeMatrixMock verify];
}
Strictly speaking, we don’t have to verify the combo box mock because it doesn’t have any expectations but it’s good practice to verify all mocks in the tear down, especially if the same mocks are used for multiple tests. By the way, by default the mocks also have fail-fast behaviour; when they receive a method that wasn’t stubbed or expected, they raise an exception right away. Detecting something that wasn’t expected can be done right way, detecting that something that was expected didn’t occur must be trigger by the user.
Now, if we run this test with an empty implementation of historyURLSelected: it will fail when we tell the server type matrix mock to verify because the expected method hasn’t been called. The error message will look something like this:
Unknown.m:0: error: -[CCMPreferencesControllerTest testSelectsServerTypeWhenHistoryURLIsSelected] : OCMockObject[NSMatrix]: expected method was not invoked: selectCellWithTag:0
Adding an implementation like the following one adds the right functionality and makes our test pass.
@implementation CCMPreferencesController
- (void)historyURLSelected:(id)sender
{
NSString *serverUrl = [serverUrlComboBox stringValue];
[serverTypeMatrix selectCellWithTag:[serverUrl cruiseControlServerType]];
}
In summary, testing controllers becomes relatively easy when we follow this pattern:
1. Replace all UI elements with mocks; using key-value coding to access the outlets.
2. Set up stubs with return values for UI elements that the controller will query.
3. Set up expectations for UI elements that the controller should manipulate.
4. Invoke the method in the controller.
5. Verify the expectations.
I find tests following this pattern easier to write and understand than tests that load a NIB file and interact with the actual user interface elements.
Tuesday, May 13, 2008
Another major improvement of OCMock: it now supports more flexible constraints on the expected arguments. This is done in the Objective-C way and user-defined constraints don’t have to implement a formal interface, they’re just methods in the test class. As usual this release also includes several contributions from the community. More details on the OCMock page at Mulle Kybernetik.
Sunday, May 4, 2008
Of the many projects I have worked on the rewrite of the Guardian website is certainly a highlight. And in this case I can even speak about it in detail. In fact, Mat Wall from the Guardian and I presented some of our experiences at several conferences, and now the Software Engineering Radio has published a podcast in which we talk about this project.



