You are reading "the Zuulcat Archives". These are publications written by Martin Mazur between 2006 - 2015.

Future writings will be published on mazur.today.



The Zuulcat Archives


Save Time with Test / Source Toggling Macro

 Feb 17, 2009  |   Filed under: Software Development  |   Tags: .NET, Productivity, TDD, VisualStudio


For the past 2-3 years all the development I have been doing has been test driven. I don't really want to count how many hours I have spent looking for corresponding test file / source file.

Last week I remembered that I use to have the same problem doing c++ development only then it was the cpp file / h file. To solve this tedious problem a friend of mine gave me a visual studio macro to toggle cpp and h file. I figured the same should be possible for test and source file.

Most of the projects I work on still use the convention of one test suite per class. For example the Person class would be tested in the PersonTests suite. If you follow a similar pattern you can use this macro for toggling between source file and test file.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
Imports System.Windows

Public Module TestHelpers
    Const CODE_FILE_SUFFIX As String = ".cs"
    Const TEST_FILE_SUFFIX As String = "Tests.cs"

    Public Sub SwitchBetweenSourceAndTest()
        Dim currentDocument As String = ActiveDocument.Name
        Dim targetDocument As String = String.Empty

        If currentDocument.EndsWith(TEST_FILE_SUFFIX, _
        StringComparison.InvariantCultureIgnoreCase) Then
            targetDocument = SwapSuffix(currentDocument, TEST_FILE_SUFFIX, CODE_FILE_SUFFIX)
        ElseIf currentDocument.EndsWith(CODE_FILE_SUFFIX, _
        StringComparison.InvariantCultureIgnoreCase) Then
            targetDocument = SwapSuffix(currentDocument, CODE_FILE_SUFFIX, TEST_FILE_SUFFIX)
        End If

        OpenDocument(targetDocument)
    End Sub

    Private Sub OpenDocument(ByRef documentName As String)
        Dim item As EnvDTE.ProjectItem = DTE.Solution.FindProjectItem(documentName)

        If Not item Is Nothing Then
            item.Open()
            item.Document.Activate()
        Else
            Forms.MessageBox.Show(String.Format("Could not find file {0}.", documentName), _
            "File not found.")
        End If
    End Sub

    Private Function SwapSuffix(ByRef file As String, ByRef fromEnd As String, _
    ByRef toEnd As String) As String
        Return Left(file, Len(file) - Len(fromEnd)) & toEnd
    End Function
End Module

I have mine mapped to alt-O.

If you haven't used Visual Studio macros before you will get a annoying balloon every time you trigger the macro. Check out "How to disable Visual Studio macro “tip” balloon?" on Stack Overflow to solve this.