Unit Test Debug Wonkiness in Visual Studio 2012

Our team has started rolling out Visual Studio 2012, and it’s been largely issue-free. In fact, the only issue that we’ve run into is a weird one: the debugger gets screwed up while debugging unit tests. What I mean by “messed up” is that you step over a line, and it jumps down several lines, variables don’t get set; you know, wonkiness!

Luckily, we were able to find this MSDN forum post, which describes our problem and how to solve it.

The problem seems to be related to the solution test settings file. The solutions presented in the forum are to remove the old test settings file or to remove the AgentRule section from the file. We tried these, and it worked for us, too.

Looking a little deeper, we found that the issue occurred when debugging unit tests–running them worked fine–in VS2012 for a solution created in VS2010 with code coverage enabled. Even with all that, the issue did not occur regularly. It worked fine on my machine, but not on my colleague’s. We removed the old test settings file but re-enabled code coverage 2010-style from within 2012 to maintain backward compatibility.

From the same forum post, there is a link to the issue on Microsoft Connect, but the issue has been “deferred” by Microsoft’s development team.

Xsd2Code in Visual Studio 2012

At the time of writing this, Xsd2Code does not install nicely in VS2012. It’s easy enough to “copy” your install from VS2010, though. Here’s a summarized version of adrianot75’s solution.

  1. Copy Xsd2Code.Addin.Addin from the VS2010 Addins directory to the VS2012 Addins
    • From: %UserProfile%\My Documents\Visual Studio 2010\Addins
    • To: %UserProfile%\My Documents\Visual Studio 2012\Addins
  2. Edit the Addin file to include an extra element for version 11.0
      <Name>Microsoft Visual Studio</Name>

NuGet-ty Goodness

NuGet has been slowly becoming one of my favorite development tools. There are a number of third party projects that I use pretty regularly. Rhino Mocks, jQuery, SpecFlow, and Enterprise Library, to name a few. In the past, I’ve kept a repository of these DLLs. When I start a new project that needs one of them, I copy the DLL into the new project directory and add a reference.

NuGet takes care of all that for me. It’s an online repository of packages, and I can add references to the packages using the NuGet Package Manager. It’s awesome because now I don’t have to remember where I saved the newest DLLs. I just install the package I need and move on. It’s great!

If you’re new to NuGet, you should definitely try it out. It’s easy and convenient, perfect for big projects and one-shot throwaways, alike. Want to learn more? Read the overview. But really, you should just try it out. I heard about it long ago, but I didn’t really get it until I started using it.

Here’s my ultra-quick-start guide:

  1. Install the Visual Studio Extension
  2. Right-click your project’s References > Manage NuGet Packages
  3. Search for and install packages

That’s it! The package will be installed, relevant files will be created in a packages sub-directory in the solution directory, and references and files will be copied into the project. Try it out; I guarantee you’ll love it!

See What Other Users Have Checked Out in TFS

There are lots of good reasons why you might want to identify which files are checked out by your fellow TFS users. Maybe you’re going to merge a branch and want to make sure everybody’s changes get included. Or perhaps an intern has gone back to school. Regardless of the reason, and whether you’re looking for all users or a specific user, it’s very easy to do!

If you’re a point-and-clickster, and you like working within the friendly confines of the Visual Studio IDE, you’ll be happy to know that there’s a menu option. Note this menu option is installed with the Visual Studio Team Foundation Server Power Tools, available from the Visual Studio Gallery.

  1. File > Source Control > Find in Source Control > Status…
  2. Find

But don’t fret if you’re a command-line purist, either. Microsoft’s got you covered with the tf status command. Here are some sample usages:

c:\tfs\tf status /user:*
c:\tfs\tf status /user:dave
c:\tfs\tf status c:\SomeOtherDir /recursive

Regular Expression Searching in Visual Studio 2012

One of the recurring themes throughout the enhancements made in Visual Studio 2012 is improved searching. There are search boxes everywhere: in the title bar, in Solution Explorer, in Test Explorer… Everywhere!

In addition to making searches more accessible, they’ve also improved and simplified support for regular expressions. Regular expression searching is something that seemed like it existed in earlier version of Visual Studio, but they used their own, custom syntax which made it difficult and unintuitive to use.

In Visual Studio 2012, regular expression searching is extremely easy–relatively speaking–to use and very intuitive. When you press CTRL+F to bring up the search window, there’s a regular expression toggle button. Click the button, and your search criteria will be interpreted as a regular expression.

That’s all good and well, but what’s really cool is that you can use capture groups for finding and replacing. How many times have you had to go through a file making the same change based on a pattern over and over again?

Here’s an example of finding/replacing with regular expressions and capture groups:

Find:    var(?<x>dog|cat)
Replace: varSuper${x}

Will replace "vardog", "varcat", "varDOG"
With "varSuperdog", "varSupercat", "varSuperDOG"
But not replace "var dog" or "dog"

How cool is that!?

Read more about using regular expressions in Visual Studio here.


BDD in .NET with SpecFlow

Yesterday, I was invited to sit in on a demo/discussion about behavior-driven development (BDD) with SpecFlow. As a self-proclaimed unit test enthusiast, I was excited right away.

I’ve been doing my own, made-up version of BDD for a while. For example, I would have a function that calls several sub-methods. I’d mock the sub-methods and write tests to verify that the sub-methods were called. Then I’d move to the next “layer” by implementing the sub-methods in a similar fashion, repeating until I hit the bottom layer, where the actual work happens.

The problem with that approach is that all tested behaviors relate to the code and not business requirements or real-world scenarios. SpecFlow fixes that by using a Gherkin parser, allowing you to write test scenarios using business-readable, domain-specific language instead of code.

Here’s how you can get started with SpecFlow and Visual Studio. This tutorial is basically a modified version of the Project Setup Guide on the SpecFlow site. I ran into a couple issues with their tutorial, though, and their tutorial also doesn’t get much into implementing the application logic to fix unit tests once they’re generated.

Installing SpecFlow

SpecFlow is included in the Visual Studio Extensions Gallery, so installing it is a breeze.

  1. Open Visual Studio, and go to Tools > Extensions and Updates (Extension Manager in VS2010)
  2. Select the Online gallery
  3. Search for “SpecFlow”
  4. Install it!

Nice, now you’re ready to create your first test project.

Creating your first test project

SpecFlow tests are defined as “features” that have multiple scenarios. There is a small amount of project setup that needs to be done, but it’s not too bad and you can be up and running in just a few minutes.

  1. In Visual Studio, create a new Unit Test Project
  2. Install SpecFlow via NuGet
    • PM> Install-Package SpecFlow
    • I had to manually add the unit test provider to my app.config:
      <?xml version="1.0" encoding="utf-8"?>
          <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
          <unitTestProvider name="MsTest" />
  3. Add a SpecFlow Feature to your project
  4. Generate Step Definitions by right-clicking in your newly created feature file

  5. Run your scenario by right-clicking in the feature file

    • Right-clicking in the feature and choosing Run SpecFlow Scenarios produced an error for me; I’ll be looking into this
    • I instead ran the unit tests as usual, and that worked fine
  6. Implement your code/step definitions until you have a passing test
    • I added my class-to-be-tested to the same file as my step definitions for brevity
      namespace adamprescott.net.SpecFlow.FirstProject
          using Microsoft.VisualStudio.TestTools.UnitTesting;
          using System.Collections.Generic;
          using System.Linq;
          using TechTalk.SpecFlow;
          public class AddingMaching
              private List<int> _numbers = new List<int>();
              private int _sum;
              public int Screen
                  get { return _sum; }
              public void EnterNumber(int num)
              public void PressAdd()
                  _sum = _numbers.Sum();
          public class MyFirstFeatureSteps
              private AddingMaching _addingMachine;
              public MyFirstFeatureSteps()
                  _addingMachine = new AddingMaching();
              [Given(@"I have entered (.*) into the calculator")]
              public void GivenIHaveEnteredIntoTheCalculator(int p0)
              [When(@"I press add")]
              public void WhenIPressAdd()
              [Then(@"the result should be (.*) on the screen")]
              public void ThenTheResultShouldBeOnTheScreen(int p0)
                  Assert.AreEqual(p0, _addingMachine.Screen);
    • The example shows a simple AddingMachine class with implemented steps to pass the default feature scenario
      Feature: MyFirstFeature
      	In order to avoid silly mistakes
      	As a math idiot
      	I want to be told the sum of two numbers
      Scenario: Add two numbers
      	Given I have entered 50 into the calculator
      	And I have entered 70 into the calculator
      	When I press add
      	Then the result should be 120 on the screen

That’s it! Now you should have a passing unit test that verifies the business-language requirement. You can add more scenarios to your feature file with different values and/or steps. Note that if you add more steps, you’ll probably need to re-generate step definitions. When you do this, only new step definitions will be generated. I recommend using the Copy methods to clipboard button in the Generate Step Definitions dialog to avoid overwriting the previously created and implemented step definitions.

A “Shim-ple” Tutorial With Microsoft Fakes

I’ve written previously about using Rhino Mocks to write unit tests for hard-to-test code, but with the release of Visual Studio 2012 comes a new way to work around those not-so-test-friendly areas: Microsoft Fakes. For those of you familiar with Microsoft Research’s Moles project, Microsoft Fakes is simply the next version. Fortunately, Microsoft decided this offering was valuable enough to be included in the latest version of Visual Studio.

What is Fakes, you might be grammatically-awkwardly asking yourself. If I had to describe Microsoft Fakes in a sentence, I’d say this: Microsoft Fakes allows you to intercept any method call and provide a substitute implementation, including calls to static and non-virtual methods. Sounds powerful, right? Well, it is.

Getting started with MS Fakes is refreshingly easy, too. The integration with Visual Studio allows you to skip the hard parts and get right to the meat: hooking up the fakes to work with the code you’re testing. This post will show you how to write a unit test for a simple FileReader class that has a single Read method that–you guessed it–reads a file. I’ll walk you through the entire process from scratch to hopefully avoid any confusion. So let’s do it!

  1. Open Visual Studio 2012
  2. Create a new Visual C# Class Library project
  3. Create the FileReader class:
    namespace adamprescott.net.FakesTutorial
        using System.IO;
        public class FileReader
            private readonly string _path;
            public FileReader (string path)
                _path = path;
            public string Read()
                using (var fs = new FileStream(_path, FileMode.Open))
                    var sr = new StreamReader(fs);
                    return sr.ReadToEnd();
  4. Add a new Unit Test Project to the solution
  5. Add a reference to the Class Library project from the Unit Test Project
  6. Create the fakes assembly by right-clicking System in the Unit Test Project’s References and selecting “Add Fakes Assembly”
  7. Create the FileReaderTest class:
    namespace adamprescott.net.FakesTutorial.Tests
        using Microsoft.VisualStudio.TestTools.UnitTesting;
        public class FileReaderTest
            public void TestMethod1()
                using (Microsoft.QualityTools.Testing.Fakes.ShimsContext.Create())
                    // Arrange
                    const string path = "irrelevant";
                    const string expected = "contents";
                    var target = new FileReader(path);
                    // shim the FileStream constructor
                    System.IO.Fakes.ShimFileStream.ConstructorStringFileMode =
                        (@this, p, f) => {
                            var shim = new System.IO.Fakes.ShimFileStream(@this);
                    // shim the StreamReader constructor
                    System.IO.Fakes.ShimStreamReader.ConstructorStream =
                        (@this, s) => {
                            var shim = new System.IO.Fakes.ShimStreamReader(@this) {
                                // shim the ReadToEnd method
                                ReadToEnd = () => expected
                    // Act
                    var actual = target.Read();
                    // Assert
                    Assert.AreEqual(expected, actual);
  8. Run the test, and feel great about yourself!

There are a few important things to note about the use of Fakes in the test above. First, the fakes are wrapped in a ShimsContext. This makes sense since you’re intercepting system calls; you don’t want to accidentally affect other areas being tested outside of your test. Next, note that I’m using fakes to override two different constructors. I needed to override FileStream‘s constructor to open the file and StreamReader‘s constructor to read the file. In the StreamReader shim, I also provide a shim for the ReadToEnd method and configure it to return the fake text for my test. I probably could have opted to shim just FileStream, but the faking might be less straightforward since success would rely on knowing exactly which methods StreamReader will use when ReadToEnd is called.

For more information about getting started with Microsoft Fakes, check out this article at MSDN.

5 New Features I’m Looking Forward to in Visual Studio 2012

Last week, I attended a GANG meeting where Randy Pagels gave a presentation about what’s new in Visual Studio 2012. Prior to this, I had skimmed through the product guide, and I was expecting to see some nice new features. I didn’t expect to be blown away, but I left the meeting feeling completely geeked about the new version. And, since the RTM version was made available to MSDN subscribers last week, I wasted no time in getting it installed.

So what has me so stoked? Here’s a breakdown of the top 5 features that have me drooling:

  1. Code reviews
  2. Simplified code coverage (no more instrumenting DLLs!)
  3. Suspend/resume work
  4. Quick Launch
  5. Object Browser integration into Solution Explorer

I’ve only used VS2012 for a day or two now, and I haven’t had enough exposure to give an in-depth overview of these new features, yet. Unfortunately, the two that I’m most excited about–the new code review workflow and suspend/resume work–require a TFS upgrade, so I won’t be able to really test them until our IT department does that. I’m looking forward to using the other three right away, though!

Read more about What’s New in Visual Studio 2012 on MSDN.

Filter Pending Changes By Solution in TFS

I just learned about a neat feature in Visual Studio’s Pending Changes window: filter by solution. If you’re viewing pending changes and have a solution open, you can use this toggle button to filter the list of files in your Pending Changes to only files included in that solution. This is a great way to ensure you’re only checking in changes that are related to the task or story that you’re working on when multitasking or managing several works-in-progress.


Online Font Converter

I was looking to spice things up with a new font in Visual Studio, but I ran into a slight snag: the font I wanted to use–Inconsolata–was an OpenType font and wouldn’t display in the Fonts and Colors settings in VS.

I found this handy post that directed me to an online font converter that worked swimmingly. Nice!

%d bloggers like this: