Tuesday, December 21, 2010

Assert.DoesNotThrow... why does it exist?

Take a look at this test:

[Test]
public void TestSomething()
{
   Assert.DoesNotThrow(MethodUnderTest);
}

It seems to me that it is functionally equivalent to this test:

[Test]
public void TestSomething()
{
    MethodUnderTest();
}

In other words, Assert.DoesNotThrow is the same as writing a test with no assertion. Is it really enough that the code runs without throwing an exception? Presumably the method under test is doing something, so shouldn't you verify those results with a stronger assertion?

Tuesday, December 7, 2010

AsyncController and custom action invokers

If you are trying to get AsyncControllers to work, you might run into this gem when you try to test your controller:

The resource cannot be found

If this happens to you, a custom action invoker is likely to be the culprit. In my case, I was using Castle Windsor, and I had extended ControllerActionInvoker to provide dependency injection to my action filters. My action invoker looked something like this:



And this is how I had registered the action invoker with Windsor (this assumes you are using a controller factory that is aware of Windsor):




All I had to change to fix the problem was to make my custom action invoker inherit AsyncControllerActionInvoker instead:



AsyncControllerActionInvoker implements IAsyncActionInvoker and adds a few new methods. Depending on what you are trying to accomplish with your custom invoker, you may need to override a few of these new methods as well.

Interestingly enough, I did not have to change how the invoker was registered with Windsor.

Monday, December 6, 2010

Using AsyncController with NServiceBus

With NServiceBus sometimes you do not want to allow a web request to complete until you have received some response from your message handler. For example, suppose you have defined the following message handler that returns a response code on success:

public class TestMessageHandler :
    IHandleMessages<TestMessage>
{
    public IBus Bus { get; set; }

    public void Handle(TestMessage message)
    {
        //Do something interesting...
        Bus.Return(0);
    }
}

This is a perfect scenario for using the asynchronous page API. It allows you to execute a potentially long-running operation on a separate thread outside of the IIS thread pool. While this thread is executing, the original request thread is returned to the thread pool. As a result, the asynchronous page API is great for I/O bound operations, since you keep threads in the thread pool ready to service requests and the new thread spends most of its time blocked on I/O. NServiceBus supports the asynchronous page API out of the box:

Bus.Send(new TestMessage()).RegisterWebCallback(callback, state);

Unfortunately, RegisterWebCallback does not work with ASP.NET MVC. If you are using ASP.NET MVC, you can use AsyncController, which was introduced in ASP.NET MVC 2. The following code illustrates how you might use AsyncController to wait for a response the message handler:

public class TestController : AsyncController
{
    private IBus bus;

    public TestController(IBus bus)
    {
        this.bus = bus;
    }

    public void IndexAsync()
    {
        AsyncManager.OutstandingOperations.Increment();

        bus.Send(new TestMessage()).Register(Callback);
    }
    public ActionResult IndexCompleted()
    {
        return View();
    }
    
    private void Callback(int responseCode)
    {
        AsyncManager.OutstandingOperations.Decrement();
    }
}

As you can see, the AsyncController API is a little awkward (though it is an improvement over the asynchronous page API, in my opinion), but it is a small price to pay for scalability.

Saturday, August 14, 2010

Ctrl-C and the NServiceBus generic host

Ten posts and almost a whole year later, my very first post about NServiceBus is still by far my most popular. So here is some more NServiceBus-y goodness.

Last week a coworker came to me asking for help with a self-hosted NServiceBus application. He had a small console application set up to test NServiceBus and it worked beautifully in all but one case. When he killed the application with Ctrl-C, the message being processed was always lost. At first I thought maybe the application was not using a transactional endpoint, but it was configured to do so. I did not see the same behavior with the generic host running in console mode, so I figured the generic host was handling Ctrl-C somehow. A quick search turned up the CancelKeyPress event. I opened up the generic host in reflector, and, on a hunch, navigated to the TopShelf.Internal.Hosts namespace (the generic host internalizes another excellent open source project called TopShelf). Sure enough, the TopShelf console host handles the CancelKeyPress event, and ultimately allows all of the worker threads in NServiceBus to finish handling messages before shutting down.

One question this brought up is what happens if someone pulls the plug on my machine after a message has been received, but before it has been processed? My impression was that a transactional endpoint would take care of this, but now I'm not so sure.

Tuesday, July 27, 2010

Over-testing: the data-driven edition

Learning to test at the right level of abstraction is tough. A common mistake involves the abuse of data-driven testing tools. Data-driven testing tools, like TestCase in NUnit, are convenient and powerful. You can write a lot of tests really fast, but if you're not careful, you can end up repeating yourself.

For example, suppose we define the following (woefully oversimplified) utility function to test if a string is a valid email address:

public static bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"\w+@\w+\.com");
}

The test suite for this function should be complete. A data-driven approach works really well here:

[TestCase("a@test.com")]
[TestCase("1@test.com")]
//... lots more
public void TestValidEmail(string email)
{
    Assert.That(IsValidEmail(email));
}
[TestCase(null)]
[TestCase("not an email address")]
//... and so on
public void TestInvalidEmail(string email)
{
    Assert.That(IsValidEmail(email), Is.False);
}

Now, suppose we use this method in some application logic:

public void SendConfirmation(string message, string email)
{
    if (!IsValidEmail(email))
    {
        throw new ArgumentException("email");
    }
    SendEmail(message, email);
}

Awesome, let's test this bad boy... er, I mean here's the test we wrote before writing the method:

[TestCase("a@test.com")]
[TestCase("1@test.com")]
//... lots more
public void TestSendEmailIfValid(string email)
{
    SendConfirmation("test", email);
    //Assert sends email...
}
[TestCase(null)]
[TestCase("not an email address")]
//... and so on
public void TestSendEmailThrowsIfInvalid(string email)
{
    SendConfirmation("test", email);
    //Assert throws exception...
}

Okay, stop... do we really need to re-test every single valid and invalid email address? Data-driven tests make this easy, but that doesn't make it right. In this function, there are really only two paths that matter: an invalid email address throws an exception, and sending an email successfully. Let's try again:

public void TestSendEmailIfValid(string email)
{
    SendConfirmation("test", "validemail@test.com");
    //Assert sends email...
}
public void TestSendEmailThrowsIfInvalid()
{
    SendConfirmation("test", "not an email address");
    //Assert throws exception...
}

Mockists might even take this so far as to stub out the IsValidEmail function for the purposes of testing this function, but for this simple case, it might be overkill since IsValidEmail has no external dependencies to begin with.

In the real world, this kind of mistake is harder to spot. Generally, if you have an explosion of TestCase attributes covering all kinds of permutations, consider revisiting the code under test. There may be some opportunities to simplify both your code and your test suite.

Saturday, July 17, 2010

JavaScript - apply invocation pattern part 2

In my last post I promised a real-world example of the apply invocation pattern. The truth is it was getting late, and I didn't feel like writing anymore. However, one of my coworkers called me out, most likely because he's a JavaScript ninja and wants to put me in my place. In an effort to deny him the satisfaction, I'll steal an example from people who are smarter than I.

If you use jQuery, you've probably used the each function at some point. The each function works something like this (what follows is a vast oversimplification, see here for the actual implementation):

jQuery.extend({
  each: function(array, callback) {
    for (var i = 0; i < array.length; i++) {
      var value = array[i];

      //Apply callback with "this" as the current value
      callback.apply(value, [i, value]);
    }
  }
});

Now we can use the each function like this:

var sentence = '';
var words = ['hello', ' ', 'world', '!'];
jQuery.each(words, function() {
  sentence += this;
});
//sentence == 'hello world!'

Tuesday, July 13, 2010

Things your parents never told you about JavaScript - Apply invocation pattern

So, yeah, it's been a while... okay, it's been more than a while. I'm sure my 8 followers missed me. Anyway, I recently had the opportunity to learn a whole mess of new stuff, and I wanted to start writing some of it down. I had a 3 week fling with Ruby, followed by a longer affair with JavaScript. I was a static language guy for the last 3 years, so all this dynamic nonsense had my head spinning... and you know what?

I liked it.

I always thought of JavaScript development as painful; a sort of necessary evil. Turns out there's an obscenely powerful language there, if you go looking for it (incidentally, start by looking here). Among those powerful features are first-class functions. For example, suppose I run the following code:

var greeter = {
  name: 'Mike',
  greet: function() {
    return 'hello ' + this.name;
  }
};

greeter.greet(); // -> 'hello Mike'

Nothing shocking there, right? Well, I can actually reach into the greeter object and steal the greet function:

var greet = greeter.greet;
greet(); // -> 'hello '

Okay, kind of cool, but not quite the expected result. Where did my name go? When you grab a function that references this and invoke it, you need to tell JavaScript what context you want to execute it in. The built-in JavaScript Function object has a method called apply which lets you set the value of this (it also lets you pass an argument array if you want to):

var bob = {
  name: 'Bob'
};

greet.apply(bob); // -> 'hello Bob'

This is called the apply invocation pattern. What can you do with it? That'll have to wait for another post...

Thursday, March 11, 2010

Re-throwing exceptions in C#



What is the difference between the following two blocks of code?

// #1
void HandleException()
{
    try
    {
        //Do something...
    }
    catch (Exception e)
    {
        throw e;
    }
}

// #2
void HandleException()
{
    try
    {
        //Do something...
    }
    catch (Exception e)
    {
        throw;
    }
}

Both blocks catch and re-throw an exception. The first block re-throws the caught exception, the second block does not specify anything to throw. The main difference between these blocks becomes apparent when the exception is logged higher up in the call stack. The stack trace for the first code block will be missing anything that came before the throw. The second code block will contain the full stack trace. This can be the difference between life and death when trying to diagnose an issue in production.

Wednesday, January 6, 2010

Castle Windsor: Order Matters

I've been learning a lot about Castle Windsor lately. I ran into something that surprised me yesterday. Suppose you have the following class hierarchy:
interface Service
{
}

class ServiceA : Service
{
}

class ServiceB : Service
{
}
What do you think the output from this code will be?
var container = new WindsorContainer();

container.Register(Component
    .For<Service>()
    .ImplementedBy<ServiceA>());
container.Register(Component
    .For<Service>()
    .ImplementedBy<ServiceB>()
    .Named("serviceb"));

var service = container.Resolve<Service>();

Console.WriteLine(service.GetType().Name);
If you said ServiceA, then you were right! Now, what about the output from this code?
var container = new WindsorContainer();

container.Register(Component
    .For<Service>()
    .ImplementedBy<ServiceB>()
    .Named("serviceb"));
container.Register(Component
    .For<Service>()
    .ImplementedBy<ServiceA>());

var service = container.Resolve<Service>();

Console.WriteLine(service.GetType().Name);
If you said ServiceB, then maybe the title of this post gave the answer away. I expected the named service to be a special case. In other words, I thought asking for a Service implementation would always give me ServiceA, unless I specifically asked for ServiceB by name.