Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Up Test Method with different inputs

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

like image 319
Gobliins Avatar asked Jan 03 '13 12:01

Gobliins


People also ask

How many types of methods we can test by using unit testing?

There are 2 types of Unit Testing: Manual, and Automated.

What is Testcontext C#?

Used to store information that is provided to unit tests.

What is ClassInitialize attribute in Mstest?

The method decorated by [ClassInitialize] is called once before running the tests of the class. In some cases, you can write the code in the constructor of the class. The method decorated by [ClassCleanup] is called after all tests from all classes are executed.


1 Answers

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
}
like image 200
Sergey Berezovskiy Avatar answered Sep 19 '22 08:09

Sergey Berezovskiy