lunes, octubre 06, 2008

Learning with Tests (MessageBroker in NInject)

A great way to learn a few coding practices is to get an open source project (one good, don't get the first thing you see en codeplex) and trying to understand the code, how they apply patterns, use certain classes or reuse code through the project. The best way to start (with most of the good projects) is with the tests.

I have been playing lately with Ninject, a Dependency Injection Framework,  it's well designed, auto-documented and documented (probably too much documentation at the code level), the downside is that the wiki, the blog posts and tutorials barely cover the basics. However, the tests do a good job to describe the project at a higher level. As an example an example we can see one of the tests for the MessageBrokerModule.

public void OnePublisherOneSubscriber()
using (var kernel = new StandardKernel(new MessageBrokerModule()))
PublisherMock pub = kernel.Get<PublisherMock>();
Assert.That(pub, Is.Not.Null);

SubscriberMock sub = kernel.Get<SubscriberMock>();
Assert.That(sub, Is.Not.Null);

Assert.That(sub.LastMessage, Is.Null);

pub.SendMessage("Hello, world!");

Assert.That(sub.LastMessage, Is.EqualTo("Hello, world!"));

The code is really easy to follow, first he asserts that the kernel can create instances of the publisher and subscriber, then the publisher should have a listener, the subscriber doesn't have any message and finally he sends a message than the subscriber should receive. The other tests like OnePublisherTwoSubscribers and ManyPubsManySubscribiers are similar.

No hay comentarios.: