NMock article in MSDN Magazine

An article about NMock has appeared in the October issue of MSDN Magazine. Chuffed :)

Mock Objects to the Rescue! Test Your .NET Code with NMock

Joe tries to do backflips

I’m doing a sponsored backflip to raise money for the International Autistic Research Organization.

How did this happen? I’m not totally sure, but if I recall it started in a conversation with Martin Gill, my manager, that went something like this:

J> Did you see the gymnastics and the olympics? It looked awesome!
M> Yeah. Bet you can’t do that.
J> How hard can it be? They make it look so easy. Bet I can learn to do a backflip.
M> Ok. When and where?
J> Uhmmm, four, no, six weeks. On the grass outside work.

Next thing I know, I’ve blabbed this to lots of people and the suggestion comes up that I get sponsorship to do it for charity.

So here I am, now 2 weeks into my 6 week task to learn to do a backflip. This backflip will take place unassisted on some flat grass. However, there was ambiguity in this challenge as there was disagreement about what a backflip actually is and it seems to vary from country to country.

In the UK, a backflip is where you jump backwards, spring on your hands and back onto your feet. The technical term for this is a back handspring. This is what *I* thought I’d agreed to. You know, like ninjas do down the street. QuickTime animation

In the US, a backflip is where you jump upwards, rotating a complete 360 in the air and land on your feet, without anything but your feet ever touching the ground. The technical term for this is a back somersault. QuickTime animation

So, to compromise the I’ve decided to give both a go. I will attempt three things:

1. A single back handspring.
2. Three back handsprings in a row.
3. A back somersault!

I’m asking for sponsorship for different amounts, depending on which of these I achieve. For example, Dan Bodart says he’ll sponsored me 10GBP if I achieve one handspring, 20GBP if I do three handsprings and 50GBP if I manage the somersault.

I’m learning this at home, with the help of Google (which has helped me find lots of online tutorials), a bouncy castle (a safe place to practice without breaking my neck), and Jaimie (my fiance who watches from afar and tells me what mistakes I’m making).

If you want to sponsor me, drop me an email ( my first name at truemesh dot com ) or leave a comment.

XStream article on O’Reilly XML.com

http://www.xml.com/pub/a/2004/08/18/xstream.html

A simple way to access JavaDoc attributes at runtime

It’s easy to gain access to JavaDoc attributes using QDox, however this requires you to have the source available. At runtime this isn’t always possible, unless you’re happy giving your source away.

A workaround to this is to use QDox to parse the source code at development time and serialize the resulting structures to make them available at runtime. This will work, but it’s a bit nasty as big binary files aren’t the most stable of things.

A more open approach is to bundle the source of your classes with the application, making them available at runtime, however *without* the method body implementations.

*Class with method body implementations:*

package stuff;

public class CheeseSlicer {

/** @transaction mode=isolated */
public Slice feedMe() {
// some implementation specific stuff here.. don't waste your time reading it.
if (System.currentTimeMillisMillis() % 2 == 0) {
return new CheddarSlice();
} else {
return new BrieSlice();
}
}

}

*Class WITHOUT method body implementations:*

package stuff;

public class CheeseSlicer {

/** @transaction mode=isolated */
public Slice feedMe();

}

To do this is simple. First, QDox can be used to parse the source of a class into a JavaClass. Calling JavaClass.toString() will print out the class without the body implementations (as above). This is something done at development time and the result should be written to a file that is available at runtime.

At runtime, QDox can read this file just as if it were a full-blown Java source file, making the attributes available.

JDK 1.5, of course, makes this redundant, but in the mean time…

XStream roadmap: What do YOU want to see?

I’m assessing where the next version of XStream should go. There are three major chunks of work I’d like to tackle (described below), however I can only take on one at a time and need to prioritize.

What do you want to see? Leave your comments on my blog.

1. Full support for the Java serialization specification.

Current situation: XStream uses reflection to access an objects fields and convert them to and from XML.

Problem: While this works well with most custom objects, there are many classes (particularly in the standard java and javax packages) that rely on advanced features of the serialization API, by implementing the methods, readObject(), writeObject(), writeReplace() or the methods found in java.io.Externalizable.

Solution: The default Converter in XStream could be enhanced to support these features.

Outcome: XStream should be able to serialize any object that standard Java serialization can, without any modifications.

2. Improved JVM support.

Current situation: XStream uses reflection to instantiate objects when deserializing. Using plain reflection, this requires each object to have a default constructor, which XStream will call. An ‘enhanced-mode’ is also supported that uses JVM specific calls to construct objects without ever invoking a constructor, guaranteeing no side-effects.

Problem: Currently the ‘enhanced-mode’ is only available if using the Sun 1.4 JVM or later.

Solution: Enhance the enhanced mode to support more popular JVMs, including Sun 1.3, IBM 1.4, and JRockit.

Outcome: More users can use XStream without having to make intrusive modifications to their classes.

3. Configurable mappings.

Current situation: XStream was originally designed as a tool for transparent serialization of objects (specifically for persistence or to send across the wire in messaging systems). As such, the goal was to allow XStream to figure out what the XML should look like on the fly, without forcing the mappings to be defined for each class.

Problem: An unforseen popular usage of XStream is for assembling objects from XML configuration files. However, because XStream has been designed to just figure out the XML on the fly, it does not allow users to (easily) specify their own XML structure.

Solution: To add more simple to use ‘tweaks’ to the generated XML. For example, to allow attributes to be used in some elements, alias elements based on where they appear or remove redundant tags to make the XML easier to understand.

Outcome: More flexibility for the resulting XML, without forcing users to write custom converters.

XStream 1.0.2 released

Changes:

* Many more converters for common Java types.
* Fields of type byte[] are now encoded using Base64.
* Improved support for using XStream in environments where classes are hot-redeployed.
* More…

Download: Full distribution or Jar only

xstream.codehaus.org

SiteMesh 2.1 released

SiteMesh 2.1 has been released. The main changes in this release:

* Out-of-the-box support for writing decorators in Velocity.
* Performance improvements.
* Numerous bug-fixes, particularly container-specific issues.

Read an introduction and then download.

http://www.opensymphony.com/sitemesh/

Agile Development Conference coming up…

ADC in Salt Lake City is just around the corner. I’ve heard nothing but good reports from the previous events so I’m checking it out. The line up looks great.

Apparently there are still spaces available. If you’re going, get in touch and we can meet up.

Oh and remember to come along to the personal practices session.

Unit Testing Asynchronous Code

I try to avoid using code that instantiates threads from unit-tests. They’re awkward to write, brittle and I would rather extract the controlling thread, using the test as the controller. However there are times when it’s unavoidable.

Here’s an example. A PriceFinder is a class that goes and retrieves a price for a symbol asyncronously, returning immediately. Sometime later it receives a response and performs a callback on a handler. I’ve left out the implementation of how it actually does this (maybe a web-service, database call or JMS message).

public class PriceFinder {
 public void findPrice(String symbol, PriceHandler handler) { ... }
}

public interface PriceHandler {
 void foundPrice(Price price);
}

To test this, a handler can be used from the test case that records what is passed in. The test can then wait for a specified time and assert that the correct result is received. If the asyncronous code does not complete within the specified time, the test will fail (suggesting the code is either running very slowly or is never going to complete).

public class PriceFinderTest extends TestCase {

 private PriceFinder finder = new PriceFinder();
 private Price receivedPrice;

 public void testRetrievesAValidPrice() throws Exception {
  finder.findPrice("MSFT", new PriceHandler() {
   public void foundPrice(Price price) {
    receivedPrice = price;
   }
  });

  // Smelly!
  Thread.sleep(2000); // Wait two seconds.
  assertNotNull("Expected a price", receivedPrice);
 }

}

However, this sucks as it will slow your test suite right down if you have loads of tests using Thread.sleep().

A less time consuming way to do it is by using wait() and notify() on a lock. The handler notifies the lock and the test waits for this notification. In case this notification never happens, a timeout is used when calling wait().

public class PriceFinderTest extends TestCase {

 private PriceFinder finder = new PriceFinder();
 private Price receivedPrice;
 private Object lock = new Object();

 public void testRetrievesAValidPrice() throws Exception {
  finder.findPrice("MSFT", new PriceHandler() {
   public void foundPrice(Price price) {
    receivedPrice = price;
    synchronized(lock) {
     lock.notify();
    }
   }
  });

  synchronized(lock) {
   lock.wait(2000); // Wait two seconds or until the
   // monitor has been notified.
   // But there's still a problem...
  } 
  assertNotNull("Expected a price", receivedPrice);
 }

}

This optimistic approach results in fast running tests while all is good. If the PriceFinder is behaving well, the test will not wait any longer than the PriceFinder takes to complete its work. If PriceFinder has a bug in it and never calls the handler, the test will fail in at most two seconds.

However, there’s still a subtle issue. In the case that the PriceFinder is really fast, it may call notify() before the test starts wait()ing. The test will still pass, but it will wait until the timeout occurs.

This is where threading and synchronization get messy and beyond me. Doug Lea has a nice little class called Latch in his concurrency library (available in JDK 1.5 as CountDownLatch). A latch can only be locked once, once released it will never lock again.

public class PriceFinderTest extends TestCase {

 private PriceFinder finder = new PriceFinder();
 private Price receivedPrice;
 private Latch latch = new Latch();

 public void testRetrievesAValidPrice() throws Exception {
  finder.findPrice("MSFT", new PriceHandler() {
   public void foundPrice(Price price) {
    receivedPrice = price;
    latch.release();
   }
  });

  latch.attempt(2000); // Wait until the latch is released
  // or a timeout occurs.
  assertNotNull("Expected a price", receivedPrice);
 }

}

That’ll do it.

How to host your own private CVS repository

Here’s a quick way to host your own remote private CVS repository, accessible via SSH.

All you need is an SSH enabled shell account on a UNIX box that has the CVS client installed. If the box doesn’t have a cvs client installed, you should be able to download a binary (or compile source) and place it in your local path. If you have webspace somewhere, chances are you’ve got everything you need.

Assuming, the server is foo.myserver.com, your username is myuser and your home dir on that server is /home/myuser, here are the steps:

* SSH to foo.myserver.com
* mkdir /home/myuser/cvsroot
* cvs -d /home/myuser/cvsroot init

Now, you can access your private CVS repository from anywhere using the CVSROOT :ext:myuser@foo.myserver.com:/home/myuser/cvsroot.