Visual studio parameterized unit test like java

烈酒焚心 提交于 2019-12-06 01:48:30

问题


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.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/11667868/visual-studio-parameterized-unit-test-like-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!