9

In a Java test environment I can use parameterized unit tests as in the following code:

@RunWith(value = Parameterized.class)
public class JunitTest6 {

    private int number;

    public JunitTest6(int number) {
        this.number = number;
    }

    @Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
        return Arrays.asList(data);
    }

    @Test
    public void pushTest() {
        System.out.println("Parameterized Number is : " + number);
    }
}

How can I do this in a Visual Studio unit test project? I can`t find any parameterized attribute or any sample like this.

Kjartan
  • 18,591
  • 15
  • 71
  • 96
bayramucuncu
  • 1,014
  • 10
  • 20

3 Answers3

10

Using the NUnit framework, you would pass parameters to a test like this:

[TestCase(1, 2, 3)]
[TestCase(10, 20, 30)]
public void My_test_method(int first, int second, int third)
{
    // Perform the test
}

This will run the two separate times, passing in the values 1, 2, 3 in the first run, and 10, 20, 30 in the second.

Edit: For an overview of available test runners for NUnit, see this SO question

Community
  • 1
  • 1
Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • 1
    TestCase attribute is not exits in NUnit or Visual Studio Default Test tool – bayramucuncu Jul 27 '12 at 07:45
  • 1
    Does too! ;) : http://www.nunit.org/index.php?p=testCase&r=2.6 Note that this is a different test-framework from the buildt-in one in VS. See the Getting Started guide here: http://www.nunit.org/index.php?p=getStarted&r=2.6 By itself, NUnit-test can not be run directly in VS. There are however, other test-runners that can run them for you. I personally use the Resharper testrunner, and would recommend it if possible. See this for a little more info: http://stackoverflow.com/questions/336655/what-is-the-best-nunit-test-runner-out-there – Kjartan Jul 27 '12 at 08:25
2

This is now also possible via the MSTest 2 framework.

It comes with a 'DataTestMethod' attribute and related 'DataRow' attributes. Which makes it similar in how NUnit works.

Here are some good examples on how to use it.

Jakub Kaleta
  • 1,740
  • 1
  • 18
  • 25
1

If you're okay with referencing NUnit, check out the page for Parameterized Tests. Support for inline-static and dynamic data values.

If you don't want to use NUnit for some reason, MSTest or VS Unit testing supports getting inputs from a CSV, XML or DB. Inline support is available via an extension. Dynamic support not yet.. you'd have to add the dynamic code to your test method if you want to dynamically compute inputs/outputs.

Jon
  • 9,156
  • 9
  • 56
  • 73
Gishu
  • 134,492
  • 47
  • 225
  • 308