Wednesday, April 01, 2009

MXUnit ExpectedException

I'm glad to see the next minor release of MXUnit :) I'm even happier to see ExpectedException make it into the release. I'd been doing a lot of development in Java and using the latest JUnit and the expected exception annotation was so nice. When I went back to writing test cases for Fusebox I found myself avoiding writing tests that would throw errors (like testing bad paths for Fusebox parsed files). Well long story short I found myself one night debugging something in Fusebox only to find Fusebox should have been throwing an error. Since I never tested for it I never caught that Fusebox was not throwing an error. That motivated me enough to spend the 30 or so minutes it took me to write a couple test cases and add the functionality to MXUnit.

So the old way to test for an error was something like this:

<cffunction name="ensure_error_on_load_extentions_with_bad_path">
<cftry>
<cfset extManager.loadExtensions(getDirectoryFromPath(getCurrentTemplatePath()) & '/notthere') />
<cfset Fail("Last line should have thrown an error") />
<cfcatch type="mxunit.exception.AssertionFailedError">
<cfrethrow>
</cfcatch>
<cfcatch type="fusebox.BadDirectory" />
<cfcatch type="any">
<cfset debug(cfcatch) />
<cfset fail("Bad Error")>
</cfcatch>
</cftry>
</cffunction>

Now all we have to do is this:

<cffunction name="ensure_error_on_load_extentions_with_bad_path" mxunit:expectedException="fusebox.BadDirectory">
<cfset extManager.loadExtensions(getDirectoryFromPath(getCurrentTemplatePath()) & '/notthere') />
</cffunction>

I love the feature, and I hope others enjoy it too.

3 comments:

billy said...

Adam, thanks for this contribution! It's awesome. I now see this as a "must have" in any kind of test framework or testing I do.

bill

Tracy Logan said...

Just came in super handy for some division-by-zero checking -- thanks, Adam!

Chris Phillips said...

In case others were wondering, here is the CF9 script syntax for that:

/**
* @mxunit:expectedException "expected.exception.type"
**/
public void function test_some_thing() {
var foo = do.some.thing()
}