Visual Studio unit testing - multiple cases like Nunit
Asked Answered
A

3

13

In Nunit one can reuse a test method for multiple cases.

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

How can I do this in Visual Studio's test framework?

Airworthy answered 12/9, 2012 at 15:15 Comment(1)
Possible duplicate of Does MSTest have an equivalent to NUnit's TestCase?Impedance
F
2

But of course, one can use the DataRow attribute as shown here:

[TestClass]
public class AdditionTests
{    
    [DataTestMethod]
    [DataRow(1, 1, 2)]
    [DataRow(2, 2, 4)]
    [DataRow(3, 3, 6)]
    public void AddTests(int x, int y, int expected)
    {
      Assert.AreEqual(expected, x + y);
    }
}
Fennell answered 6/6, 2022 at 1:18 Comment(1)
MS Test V2 has this feature since about 2017. But in 2012, when the question was asked and the answers were given, it was not possible with MS Test V1.Subcelestial
S
3

It is not possible out of the box. But for VS 2010 atleast you can write MSTEST Extensions to provide nearly the same feature. Check this blog. But it is not nearly as good as NUnit's TestCase.

Sweeny answered 12/9, 2012 at 15:19 Comment(0)
E
3

Unfortunately, MS Test doesn't support RowTests. However, a workaround can be hacked using the DataSource attribute. There is an example here.

Ellary answered 12/9, 2012 at 15:20 Comment(0)
F
2

But of course, one can use the DataRow attribute as shown here:

[TestClass]
public class AdditionTests
{    
    [DataTestMethod]
    [DataRow(1, 1, 2)]
    [DataRow(2, 2, 4)]
    [DataRow(3, 3, 6)]
    public void AddTests(int x, int y, int expected)
    {
      Assert.AreEqual(expected, x + y);
    }
}
Fennell answered 6/6, 2022 at 1:18 Comment(1)
MS Test V2 has this feature since about 2017. But in 2012, when the question was asked and the answers were given, it was not possible with MS Test V1.Subcelestial

© 2022 - 2025 — McMap. All rights reserved.