geek yapping

Twitter












My cool code snippet

I submitted this to the Resharper cool code snippet competition and thought I would share it with everyone else, including why it’s cool!
[Test]
public void $METHOD$_$SCENARIO$_$EXPECTATION$()
{
	$END$
}
I’ve been doing a lot of TDD lately and I am constantly writing new tests. So my number one snippet is one that creates a simple test. I’ve tweaked this template a lot, it started out with a simple test template with only one editable occurance for a name. In “The Art of Unit Testing,” Roy Osherove talks about test readability which starts with the test name itself. He suggests putting the test method name together with three components. First, name the method under test (the Act in AAA), that way related tests for the same method are easy to identify (and actually R# sorts test fixture test methods by name so this is even more useful with Code Cleanup :) ). Second, name it with a scenario, what is unique about the given context of the test (known as the Arrange in AAA). Finally, include the outcome of the test, the expectation (Assert in AAA). This way you know all of what will go into the test before you write it!

I gave his naming scheme a try and found out it offers a pit of success. If you cannot name these three parts then your test likely won’t be readable. Anyone should know what a test does without reading it, like with any method, it should be intention revealing! Without identifying a scenario explicitly, it may be blurred in several lines of setup (Arrange). Having the scenario in the name makes it explicit and makes me keep it simple (I hate long method names). The test may have too many expectations, again, I hate long method names so if I find myself putting multiple expectations in the name I will quickly realize I need to move the other expectations to new tests (SRP with testing)!

The same day I tried using this test method naming convention, was the same day I created this test snippet and have kept it ever since. Every time I write a test, I am very explicit and careful, which is very important with TDD, not to take on too much with any one test!

This snippet is awesome, not because of the code it creates, but because it sets myself up for success every time I use it, like having Uncle Bob Martin watching over my shoulder :)

Feedback

No comments posted yet.