FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
SOA Web Services Blog: SOA & unit testing
XML & Web Services
<![CDATA[[

Web Services and Smart Data.

by John Dorsey
THE SOFTWARE SIMPLIST

Web Services Wisdom.

by Udi Dahan
July 15, 2006

SOA & unit testing

Following up on my recent posts on SOA Testing and on the structure of services, I wanted to finish up the issue of unit testing in SOA. Since the main difference between a "regular" application and a "service" is that a service communicates only via messages/messaging, and by using a bus to keep our message handlers technology independent, if we keep them isolated from our Domain Model, then the only difference between unit testing a regular application and a service is unit testing the message handlers.

So, how do we unit test a message handler?

Well, by having an IMessageHandler interface that exposes a single "void Handle(T message);" method, all message handler classes will need to be tested via that interface. Note that a single class may implement this interface for numerous message types - this is especially important in workflow scenarios, but that's a topic for a whole 'nother post.

In order to unit test any class, the most important thing to do is understand what other classes it interacts with. In the case of a message handler, it would most commonly interact with 3 kinds of classes:

1. Domain Model classes that contain the logic
2. Persistence classes to persist changes that occur in the domain model
3. The bus to communicate changes back to the world

By keeping our Domain Model independent of cross-cutting concerns like persistence, we can then use these same classes for unit testing. The persistence and bus classes, on the other hand, need to be stubbed, or mocked out, as do any other classes that may adversely affect the unit under test.

The kinds of unit tests that are written for message handlers often look something like this:

1. Mock the bus and persistence classes and pass those objects to the unit under test (the message handler)
2. Set expectations for behavior that will occur as a result of handling the message
3. Create a message and call the "Handle" method of the handler
4. Verify that the expectations from (2) were met.

These expectations are often in the form of:
* When the "Get" method of the persistence class was called, have it return some data that we can check against later
* The "Reply" method of the bus was called, and the message passed to it of the correct type and has the correct data - checked against what was prepared by the persistence stubs

As you can see, unit testing a message handler isn't that much different than unit testing any other class. And that's the bottom line. Correctly designing your services will lead you to easy to test code, making unit testing a service just like unit testing any application.

Posted by Udi Dahan at 09:19 AM  Permalink




 
INFO-LINK