BDD Style Naming Macro for Visual Studio


I've really jumped on board with BDD (Behaviour Driven Development) in the past week.  I've been reading about it for awhile, but it wasn't until I started actually doing it on a side project of my own that I've really begun to realise how good it can be.  The natural language naming style of the 'specs' (not 'tests' anymore) in different 'contexts' is an excellent way to express through code what your systems does (or should do).

If you have no idea what I'm blabbering on about, you should probably do a google search on 'BDD' or check out the links below:

Writing software BDD style really changes the way you think about how you express what your system does through your tests/specs.  Writing specs in different 'Contexts' have enabled me to make my tests more precise and to the point.  It is definitely something that I will strive to start using for real projects in the coming few months.

Anyway, so now that you know what BDD is, I can get to the original reason I started this post: a handy BDD naming macro that speeds up your development time by formatting your naturally written sentences into a properly constructed test case shell. 

eg.  You type:

should be able to load all items

<macro executed via keyboard shortcut> and you get:

[Test]
public void Should_be_able_to_load_all_items()
{
}

Having something like this just makes writing your specs a whole lot simpler.

Now I just want to point out, I didn't come up with the idea for this macro.  It was developed originally by Scott Bellware and then evolved by Terry Hughes.  This is outlined in a blog article here.

The code for the macro shown on the link above just replaces the spaces with underscores.  I've evolved it further to also:
  • Append '()' to the end of the line
  • Prepend '[Test]' to the line above (because I'm still using NUnit as my testing/spec framework)
  • Capitalise the first letter of the spec name
  • Provide an empty method body enclosed by '{' and '}'.
As a result of the above additions, I've also changed the name of the method to 'FormatTestCaseBDDStyle()'.  This name better reflects what the method does.

Code is below:



Imports System
Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module CodeEditor

    Sub FormatTestCaseBDDStyle()

        If DTE.ActiveDocument Is Nothing Then Return

        Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
        selection.SelectLine()

        If selection.Text.Trim() = "" Then Return

        Dim prefix As String = "public void "
        Dim index As Integer = selection.Text.IndexOf(prefix)

        Dim description As String = selection.Text.Replace(prefix, String.Empty).Trim() + "()"
        description = description.Replace(" ", "_").Replace("'", "_")
        description = description(0).ToString().ToUpper() + description.Substring(1)

        selection.Text = ControlChars.Tab + _
                        ControlChars.Tab + _
                        "[Test]" + _
                        ControlChars.NewLine + _
                        ControlChars.Tab + _
                        prefix + description + _
                        ControlChars.NewLine + _
                        "{" + _
                        ControlChars.NewLine + _
                        ControlChars.Tab + _
                        "}"

        selection.EndOfLine()
        selection.LineUp()

    End Sub
End Module




So basically when you sit down to write your next spec, you just write the sentence as you would if you were speaking to a human, invoke the macro keyboard shortcut, and it does the rest for you.

For help on getting the macro setup in Visual Studio check out the following links:

Just as a side note, the project I've started using BDD on (and NHibernate too for that matter) is going to be basically a CMS for another website of mine that I'm slowly building up: www.pineappletinfeet.com.  I will be releasing the source code of this project in the future so you can see my journey with BDD.



 del.icio.us  Stumbleupon  Technorati  Digg 

 

What did you think of this article?




Trackbacks
Comments

  • 16 January 2008, 12:46 AM Will Sullivan wrote:
    Nice, I definitely like. But I made some changes when I added it to my macros.

    The two issues I have is that it won't camel case the method name, and actually writing out the method name causes intellisense to freak out. I added some code to fix the first issue (I prefer no _'s and camel casing), changed it for VS unit testing and solved the intellisense issue by allowing the method name to be extracted from a comment, i.e.: // null case test


    If DTE.ActiveDocument Is Nothing Then Return

    Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), EnvDTE.TextSelection)
    selection.SelectLine()

    If selection.Text.Trim() = "" Then Return
    Dim text As String
    text = selection.Text.Replace("//", "")
    text = text.Trim()

    Dim result As New StringBuilder()
    result.AppendLine("[TestMethod()]")
    result.Append("public void ")
    Dim parts As String() = text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
    For Each part As String In parts
    result.Append(part.Substring(0, 1).ToUpper)
    result.Append(part.Substring(1, part.Length - 1))
    Next
    result.AppendLine("()")
    result.AppendLine("{")
    result.AppendLine("}")
    selection.Text = result.ToString()
    DTE.ExecuteCommand("Edit.FormatDocument")
    selection.LineUp()
    selection.NewLine()
    selection.LineUp()
    Reply to this
    1. 16 January 2008, 7:54 AM mattcalla wrote:
      I had the same issue with IntelliSense trying to take over the world, so I turned the autocomplete of 'Letters and digits' off in my Resharper settings (Resharper had taken over the standard VS intellisense).  This allowed me to type natural sentences, and if I need to invoke intellisense I just use Ctrl+Space.
      Reply to this
  • 16 January 2008, 8:23 AM Will wrote:
    I've been using it today and determined that I suck. Here's a better version; you 1) write, in comments, one test description per line (one or more lines) 2) select all the lines 3) run the macro. It creates multiple at once, and uses VB's facilities to do upper casing. Using the TextSelection object rather than a stringbuilder makes sure indentation of new lines is correct. Also, adds your original description as a description property
    Sub FormatTestCaseBDDStyle()

    If DTE.ActiveDocument Is Nothing Then Return



    Dim selection As TextSelection = _

    CType(DTE.ActiveDocument.Selection(), _

    EnvDTE.TextSelection)



    If selection.Text.Trim() = "" Then Return



    Dim text As String

    text = selection.Text.Replace("//", "")

    selection.Text = ""



    Dim lines = text.Split(Environment.NewLine.ToCharArray(), _

    StringSplitOptions.RemoveEmptyEntries)

    Dim result As New StringBuilder()

    For Each line As String In lines

    line = line.Trim()

    selection.Text += "[Description(""" + line + """)]"

    selection.NewLine()

    selection.Text += "[TestMethod()]"

    selection.NewLine()

    selection.Text += "public void " + StrConv(line, _

    VbStrConv.ProperCase).Replace(" ", "") + "()"

    selection.NewLine()

    selection.Text += "{"

    selection.NewLine()

    selection.NewLine()

    selection.Text += "}"

    selection.NewLine()

    Next

    selection.LineUp()

    selection.LineUp()

    End Sub
    Reply to this
Leave a comment

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.