C# 使用不同的输入设置测试方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14138907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Up Test Method with different inputs
提问by Gobliins
I want to test the following method in C# for all code paths.
我想在 C# 中为所有代码路径测试以下方法。
public int foo (int x)
{
if(x == 1)
return 1;
if(x==2)
return 2;
else
return 0;
}
I've seen this pex unit testingwhere multiple inputs are tested. How can I create a unit test that accepts multiple inputs?
我见过这个pex 单元测试,其中测试了多个输入。如何创建接受多个输入的单元测试?
[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
我想避免为每个输入创建一个测试方法。我正在使用 Visual Studio 2010/2012 和 .Net 4.0
采纳答案by Sergey Berezovskiy
You can use XML, Database, or CSV datasources MS Test. Create FooTestData.xml:
您可以使用XML、数据库或 CSV 数据源 MS Test。创建 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 attributeto provide test data:
顺便说一句,与 NUnit 框架匹配更容易 - 您可以使用TestCase 属性来提供测试数据:
[TestCase(1)]
[TestCase(2)]
public void FooTest(int x)
{
// some assert
}
回答by mhoff
If using NUnit parameterized testsis the way to go
如果使用 NUnit参数化测试是可行的方法
回答by Mike Parkhill
In MS Test you can create data driventests that accept different inputs for the same test method.
在 MS Test 中,您可以创建数据驱动的测试,这些测试接受相同测试方法的不同输入。
Here's a blog post on it: http://toddmeinershagen.blogspot.ca/2011/02/creating-data-driven-tests-in-ms-test.html
这是一篇关于它的博客文章:http: //toddmeinershagen.blogspot.ca/2011/02/creating-data-driven-tests-in-ms-test.html