Tag Archives: .NET

Why won’t my iterator throw?

I ran into a spot of confusion last night doing some TDD on a method that returns an IEnumerable<T>. I was using multiple yield return statements in it which made the method an iterator and not just a normal method.

Even though I know how iterators work, I don’t use them enough to remember their idiosyncrasies. The main one being that it’s easy to “invoke” them without actually executing any of the code inside them!

To illustrate this using a highly contrived example, imagine you wrote the following test:

[Test]
public void It_throws_when_you_pass_in_null()
{
    Assert.Throws<ArgumentNullException>(
        () => MyObject.MyMethod(null));
}

And then implemented the method it tests it like so:

public static IEnumerable<object> MyMethod(object arg)
{
    if (arg == null)
        throw new ArgumentNullException("arg");

    yield return "whatever";
}

Surprise! Your test fails.

Why? Because the code in your iterator doesn’t start executing until you invoke GetEnumerator on its return value then invoke MoveNext on that.

One really quick way to force these method calls to happen is to use the ToArray extension method:

[Test]
public void It_throws_when_you_pass_in_null()
{
    Assert.Throws<ArgumentNullException>(
        () => MyObject.MyMethod(null).ToArray());
}

ToList or manually iterating over the result with foreach would work just as well.

A better way to fix this is to change your implementation so that it uses two methods:

public static IEnumerable<object> MyMethod(object arg)
{
    if (arg == null)
        throw new ArgumentNullException("arg");

    return MyMethodHelper(arg);
}

private static IEnumerable<object> MyMethodHelper(object arg)
{
    yield return "whatever";
}

Written this way, MyMethod isn’t an iterator anymore. It’s just a plain old method that gets executed the way you’d expect it to. MyMethodHelper becomes the iterator. Its code won’t get executed until you start calling MoveNext, but that’s OK because the validation code you care about already ran.

Problem solved, right? Unfortunately, this wasn’t quite my exact problem.

My method was actually throwing after it did its argument checking and while it was yielding values. There’s really no solution (that I know of) to handle this without invoking MoveNext (or something else that will invoke it for you like ToArray) until whatever condition throws your exception is triggered.

Adding ToArray to my test wasn’t a big deal, but it took me a bit of time to figure out why it was failing. I was actually setting breakpoints in my method, running the test in the debugger, and tripping out when my breakpoints weren’t hitting.

Maybe going through the trouble of writing this post will save me 10 minutes next time I write an iterator.

BehaveN

I’ve been using a Cucumber-inspired BDD framework for .NET called BehaveN at work for the past year. Today, I just released the next major version.

There’s a little documentation on the wiki, including a tutorial, but there’s a lot left that I haven’t documented yet. I’ll be getting more and more documentation up as time goes on.

It’s been pretty positively received by our product owners, QA, and most of the developers who’ve been exposed to it. It’s being used by a few outside my company, but I haven’t made any effort on “advertising” it. If anybody’s interested in giving it a try, let me know and I’ll try to fill in any of the blanks you might have.

AutoRunner Downloads

I took some time tonight to throw together a build script for producing proper releases of AutoRunner. If you don’t feel like compiling it yourself, you can get a pre-compiled version here.

I used ILMerge to merge the Growl for Windows assemblies into the executable so it’s basically a single file now.

By the way, last night on Twitter, Steve Bohlen pointed me to this port of the original autotest to .NET. I took a look at the code and it was much more complex than I was looking for. It actually builds and runs your tests every time you save which is much more often than I want.

I had AutoRunner turned on all day at work today and was loving how it would catch me breaking the tests when I wasn’t expecting it to. =)

AutoRunner

I recently came across this awesome code kata performance by Corey Haines here.

Besides enjoying and learning from his actual performance, I was really impressed by his use of a Ruby tool called autotest. (I’m not sure, but it looks like it has become autospec.)

Not being a Ruby developer, I wanted the same thing for .NET. I did some searching, but my Google-fu failed me so I spent an hour hacking together my own.

The result is called AutoRunner (I know–way creative) and its source is available on GitHub.

If you want it, you have to download the source and compile it yourself for now. (UPDATE: You can now download it here!) Run it from your favorite console (PowerShell, right?) without any arguments to see what options it accepts.

AutoRunner is a little more general purpose than autotest/autospec is. Basically, it can run any executable when any file changes.

What I wanted it for was to run nunit-console.exe whenever my current tests assembly was rebuilt. To do that, I just invoke it with the right arguments.

If you have Growl for Windows running, it will send it a notification which is pure eye candy and not necessary to actually get it to run your tests.

It’s not a Visual Studio add-in. It’s just a plain old console application. Using Visual Studio’s External Tools feature, however, it’s almost as good as an add-in. I set up an external tool with the appropriate arguments and it’s good to go for all of my projects.

To set this up for yourself, you’d create a new external tool with its command set to the path where you built AutoRunner.exe and its arguments set to something like the following (I’ve separated the options on their own lines, but you wouldn’t do that in Visual Studio):

--target $(BinDir)\$(TargetName)$(TargetExt)
--exe C:\path\to\nunit-console.exe
--pass "$(TargetName) FTW!"
--fail "Oh noes! $(TargetName) is FAIL!"

You can use whatever test runner you like, of course. Please note that you must have a file from your tests project open or selected in Solution Explorer when you activate the tool or your AutoRunner instance will be watching the wrong DLL!

It doesn’t support plug-ins the way autotest does and most of its functionality is hard-coded for now. If anybody finds it useful, let me know and maybe we can work on improving it together.

SharpTestsEx

I’ve been using Fabio Maulo‘s NUnitEx project to get fluent assertions on a personal project recently and have been loving it.

He then went and moved on to a new project called SharpTestsEx, which he intended to be framework-agnostic, but currently only worked with MSTest which prevented me from being able to use it (since I never saw a compelling reason to switch to MSTest).

Fabio was kind enough to let me make the changes necessary to remove the dependency on MSTest. A also made framework-specific versions of SharpTestsEx for MSTest, NUnit, and xUnit. The framework-specific versions aren’t really necessary, but they make the error messages a tiny bit prettier if you use the right one for the test framework you’re using.

You can read Fabio’s announcement here.

I plan on updating my personal project to using SharpTestsEx next.

I just realized I never posted about that project; I’ll have to get around to that soon. If you’re curious, it’s a behaviour-driven development framework for .NET called BehaveN. I’m using it at my work and we’re loving it.

TestDriven.NET Keyboard Shortcuts

I’m so sick of Ctrl+Tab’ing back to my test file, finding the test I want to run, right-clicking it with the mouse, and selecting Run Test(s) or Test With.

How come nobody told me that TestDriven.NET came with keyboard shortcuts? They have to be manually mapped, but once I did that, I’ve found them indispensible.

  • Alt+1 : TestDriven.NET.RunTests
  • Alt+2 : TestDriven.NET.RerunWithDefault
  • Alt+3 : TestDriven.NET.Debugger
  • Alt+4 : TestDriven.NET.RerunWithDebugger

I especially love the two shortcuts that repeat the most recent test run for me. Yeah, I know you can right-click in any file and select Repeat Test Run, but if I want to alternate between running inside or outside the debugger, I have to go find the test again. With my shortcuts, I can just hit Alt+2 or Alt+4 no matter where I am.