Skip to main content

Parameterized Unit Tests with MSTest (Metro)

I spent a long time looking for this last night as I was trying to decide if I should use MSTest, NUnit, XUnit, or something else on the Windows Store app that I've been developing.

One of the things I've used in the past with NUnit was the ability to create test cases like so:

  1. [TestCase(12,3,4)]
  2. [TestCase(12,2,6)]
  3. [TestCase(12,4,3)]
  4. public void DivideTest(int n, int d, int q)
  5. {
  6.   Assert.AreEqual( q, n / d );
  7. }

(example taken directly from the NUnit documentation here)

However, since I'd used NUnit before and since this was a side-project (no time/budget restrictions) I decided to learn some MSTest. In adding the test project and a reference to my application as well as watching a video from build on Unit Testing Windows 8 store apps I found it nice, easy, and clean. So I went looking for where this feature which to me is a huge, necessary feature and I couldn't find it... So I googled, and I googled, and I googled...

and the only thing I found was that it couldn't be done.

In giving up and going with NUnit, I installed it, changed my attributes on my classes to the NUnit TestFixture, Test, and TestCase and tried to run but it wouldn't run. It took checking the output window to realize that the nunittestexecutor wasn't being found.

Could not find test executor with URI 'executor://nunittestexecutor/'. [...]

After a bit more of looking around here and a few other places I came to the realization that with the Windows 8 store apps the NUnit extension wouldn't work due to the different .NET targets. I realized that the project type itself also was not a "Testing" project type, but a "Windows Store" specific unit testing project. The extension to run XUnit wouldn't even install for that project.

Further googling on doing parameterized "TestCase-like" unit testing with MSTest involves creating databases and "Data-driven" testing that I just did NOT want to mess with - especially since I didn't think it would work (can't use sql server compact on Windows Store Apps at this time).

But wait! I finally found it! Tucked away in a single forum post that was done quite recently I found that MSTest actually now implements a test attribute called [DataTestMethod] followed up by the [DataRow] attribute as a new feature in Visual Studio 2012 Update 1. Thus, we can rewrite the same test that was done above in NUnit, now with the equivalent in MSTest:

  1. [DataTestMethod]
  2. [DataRow(12,3,4)]
  3. [DataRow(12,2,6)]
  4. [DataRow(12,4,3)]
  5. public void DivideTest(int n, int d, int q)
  6. {
  7.   Assert.AreEqual( q, n / d );
  8. }

And additionally to help with discerning which of those cases are failing the [DataRow] attribute also has a "DisplayName" property that will be reflected in the Test Explorer pane.