Archive for December, 2007

Mocking with LINQ: Moq is here!

In these days of agile and TDD, most probably you had to deal with mocks. In such case, you have two options: create hundreds of mock classes by hand, one for each expected behavior for every unit test, or use a mock framework.

There are many mock frameworks available for .NET but all of them have one or both of the following problems:

  1. The framework rely on the member names as strings, making really difficult the refactoring sessions.
  2. The mock objects are created based on the interaction and sequences of calls.

The last problem is probably subjective, but I believe the unit tests should not rely on the interaction of the tested entity with the outside. Otherwise, these tests would be tightly coupled with the implementation making possible refactoring and optimizations almost impossible without rewriting the entire test suite.

So, how to solve these issues and what LINQ has to do with all this? Moq is the answer! And you can read the “official” announcement in the kzu’s weblog. I’ve been working with him in this project as was completely amazing to have the first prototype working in just an hour of pairing and having written just a bunch of dozens of code lines! LINQ rocks! :)

Many examples are given in the project site, but I’ll copy some of them so you can get excited:

var mock = new Mock<ICloneable>();
var clone = new object();

mock.Expect(x => x.Clone()).Returns(clone);

Assert.AreEqual(clone, mock.Instance.Clone());

I think the framework interface is self explanatory. Even for more complicated examples like this one with callbacks:

var mock = new Mock<IFoo>();
bool called = false;
mock.Expect(x => x.Do1()).Callback(() => called = true).Returns(1);

Assert.AreEqual(1, mock.Instance.Do1());
Assert.IsTrue(called);

Or even very flexible filters (powered by LINQ):

var mock = new Mock<IFoo>();

mock.Expect(x => x.Duplicate(It.Is<int>(value => value < 5 && value > 0))).Returns(() => 1);

Assert.AreEqual(1, mock.Instance.Duplicate(3));

Enjoy!

REST/POX client with WCF 3.5

Some time ago I wrote a post about how to create REST clients using WCF and taking advantage of its extensibility to obtain a type safe endpoint. My approach implied create a bunch of WCF behaviors and other extensions that intercepts the messages and customize the representation over the wire.

Now with .NET 3.5 the WCF framework is extended to support natively these kind of scenarios and is really easy and clean to use. There are some good tutorials describing these extensions, like this one.
So, I’ve put hands on these exciting tools, and migrated my previous example to use the new framework. Ideally I would just remove my customizations, configure the endpoint with a webHttpBinding and a webHttp behavior. But this wont work because in my service contract I have some operations receiving unsupported argument types like int?, DateTime? and string[]. Fortunately, one more time the WCF team did and excellent job providing us the extensibility points we need :-).

Instead of configuring directly the webHttp behavior, I’ve created a custom DeliciousWebHttpBehavior (extending WebHttpBehavior) and overriding only the GetQueryStringConverter method. The QueryStringConverter is responsible of converting the arguments to a string representation and back again. Creating a DeliciousQueryStringConverter that supports our special types is fair enough.

After that I only have to change the attributes in the operations, so for example where in the previous example says:

[OperationContract(Action = "/v1/posts/get")]
PostsResponse GetPosts(string tag, DateTime? dt, string url);

in the new version is changed by:

[OperationContract]
[WebGet(UriTemplate = "/v1/posts/get?tag={tag}&dt={dt}&url={url}")]
PostsResponse GetPosts(string tag, DateTime? dt, string url);

Happy RESTing! :-).

Download: wcfrestpox35.zip

Automatic ‘Organize Usings’ when saving files on VS2008

I really love this new feature of VS2008 that allows you to cleanup the ‘usings’ section of C# files (and I’ve been always missing this from Eclipse) but I was a bit disappointed when I found there is no choice to execute automatically before every save. Somebody please tell me if I’m wrong!
As I’m little paranoid I wrote this simple macro and reassigned the ‘CTRL+S’ shortcut to it. The try/catch is needed because it will fail with no C# editors.

Public Sub RemoveSortAndSaveSelectedItems()
    Try
        DTE.ExecuteCommand("Edit.RemoveAndSort")
    Catch
    End Try
    DTE.ExecuteCommand("File.SaveSelectedItems")
End Sub

Now this will be on my list of the very first things to do when reinstalling a development machine ;-).