Unit Testing DocumentHandlers

As I promised in a previous post, I'd like to discuss how to unit test a custom DocumentHandler. There's really nothing to it: Just create a new instance of your DocumentHandler and start invoking its members.

Here's a test of the Submit method:

 public void SubmitWillReturnCorrectDescription()
     // Fixture setup
     string anonymousXml = "<anonymous>XML</anonymous>";
     Guid anonymousMessageId = Guid.NewGuid();
     string anonymousDeviceId = "Anonymous device ID";
     IPrincipal anonymousPrincipal =
         new GenericPrincipal(
             new GenericIdentity("Someone"), new string[0]);
     string expectedDescription =
         string.Format("Message {0} was successfully submitted",
     MyDocumentHandler sut = new MyDocumentHandler();
     // Exercise system
     DocumentResponse result =
         sut.Submit(anonymousXml, anonymousMessageId,
         anonymousDeviceId, anonymousPrincipal);
     // Verify outcome
         result.Description, "Description");
     // Teardown

Since the Submit method takes four parameters, you must create these four objects prior to invoking the method. In this example, I'm naming the variables using the Anonymous Variable Naming coding idiom.

In many cases, the XML string containing the document to submit is probably the most interesting parameter, and you will likely need to write many separate tests to verify that your custom DocumentHandler correctly deals with different instances of your particular XML document format.

In this context, it's worth noting that you can obviously debug into your code when running a test, so this is a very effective troubleshooting technique. Due to the way we load and host DocumentHandlers, it's not possible to attach a debugger to a custom DocumentHandler while it's executing in Mobile Server, so debugging into a unit test is a good alternative. If your custom DocumentHandler throws an exception while executing in Mobile Server, the event log will contain a copy of the message, and you can then use this copy to reproduce the problem in a unit test.

In the test shown above, notice that I create a new GenericPrincipal instance to use as the mobileUser parameter. Be aware that any IPrincipal instance is acceptable, so I just created a GenericPrincipal because it was the easiest thing to do. When executing your custom DocumentHandler, Mobile Server doesn't use GenericPrincipal, but rather a different implementation of IPrincipal, and it makes no guarantees that it will always use the same implementation type. In other words, your custom DocumentHandler should follow the Liskov Substitution Principle.

As you can see, it's really straightforward to unit test custom DocumentHandlers. The Submit method has by far the most complex signature, so testing the FriendlyName and GetDocumentDescription members is even simpler.

Update: A follow-up post dealing with unit testing and DocumentHandlerParameters is now available.