c# - 设置具有不同输入的测试方法

标签 c# visual-studio-2010 unit-testing vs-unit-testing-framework

我想在 C# 中针对所有代码路径测试以下方法。

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

我看过这个pex unit testing测试多个输入的地方。如何创建接受多个输入的单元测试?

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

我想避免为每个输入创建一个测试方法。我正在使用 Visual Studio 2010/2012 和 .Net 4.0

最佳答案

您可以使用 XML, Database, or CSV datasources MS Test .创建 FooTestData.xml:

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

并将其设置为测试的数据源:

[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
}

顺便说一句,使用 NUnit 框架更容易匹配 - 您可以使用 TestCase attribute提供测试数据:

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

关于c# - 设置具有不同输入的测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14138907/

相关文章:

.net - 如何使用 NUnit(或者可能使用其他框架)测试异步方法?

c# - 如何修复 .net standard 2.0 项目中的 'Could not load file or assembly System.IO.Packaging, Version=4.0.3.0'

visual-studio - 在 Visual Studio 2015 中打开 VSTO 项目

c# - 刷新A gridview数据

c++ - 想逐行阅读,但 fstream 只读第一行

c++ - cppunit 断言失败时如何显示十六进制值

c# - 如何使用 Moq 对 Entity Framework 6 中的删除操作进行单元测试

c# - xml 和 & 问题

c# - 具有 Stream 类型成员的对象的 JSON.NET 序列化?

c# - Asp.net 在 GridView.AllowPaging ="true"时生成错误的 SQL 请求