Set Up Test Method with different inputs

◇◆丶佛笑我妖孽 提交于 2019-12-20 18:36:21

问题


I want to test the following method in C# for all code paths.

public int foo (int x)
{
    if(x == 1)
        return 1;
    if(x==2)
        return 2;
    else
        return 0;
}

I've seen this pex unit testing where multiple inputs are tested. How can I create a unit test that accepts multiple inputs?

[TestMethod()] //some setup here??
    public void fooTest()
    {
         //some assert
    }

I want to avoid creating a test method for each input. I am working with Visual Studio 2010/2012 and .Net 4.0


回答1:


You can use XML, Database, or CSV datasources MS Test. Create FooTestData.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Rows>
  <Row><Data>1</Data></Row>
  <Row><Data>2</Data></Row>
</Rows>

And set it as datasource for your test:

[TestMethod]
[DeploymentItem("ProjectName\\FooTestData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
                   "|DataDirectory|\\FooTestData.xml", "Row",
                    DataAccessMethod.Sequential)]
public void FooTest()
{
    int x = Int32.Parse((string)TestContext.DataRow["Data"]);
    // some assert
}

BTW with NUnit framework it's match easier - you can use TestCase attribute to provide test data:

[TestCase(1)]
[TestCase(2)]
public void FooTest(int x)
{
   // some assert
}



回答2:


If using NUnit parameterized tests is the way to go




回答3:


In MS Test you can create data driven tests that accept different inputs for the same test method.

Here's a blog post on it: http://toddmeinershagen.blogspot.ca/2011/02/creating-data-driven-tests-in-ms-test.html



来源:https://stackoverflow.com/questions/14138907/set-up-test-method-with-different-inputs

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