c# - DataTestMethods 的非编译时间常量

标签 c# unit-testing mstest

如何将 [DataTestMethod] 与非编译时常量的 [DataRow(...)] 结合使用?示例:

[DataTestMethod]
[DataRow(new DateTime(2000, 1, 1), "2000-01-01")]
[DataRow(new DateTime(2000, 2, 1), "2000-02-01")]
public void TestTime(DateTime dateTime, string expected) {
    Assert.AreEqual(dateTime.ToString("yyyy-MM-dd"), expected);
    Assert.AreEqual(dateTime.ToString("yyyy-MM-dd"), expected);
}

这将在 new DateTime(...) 上引发编译错误,因为这不是编译时常量。

最佳答案

您只能在属性中指定编译时常量,因此您不能像DataRow 那样直接向测试方法提供非常量数据。但是,您可以使用 DynamicData您可以在其中指定可以检索非常量数据的方法或属性的属性。

例如;

[DynamicData(nameof(GetTestData), DynamicDataSourceType.Method)]
[DataTestMethod]
public void TestFoo_Bar_ReturnsExpected(decimal x, decimal y, decimal expectedResult)
{
    var foo = new Foo();

    var outcome = foo.Bar(x, y);

    Assert.AreEqual(expectedResult, outcome);
}

public static IEnumerable<object[]> GetTestData()
{
    yield return new object[] { 0M, 5M, 0M };
    yield return new object[] { 5M, 5M, 25M };
}

关于c# - DataTestMethods 的非编译时间常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45997718/

相关文章:

.net - 避免对单个类中的所有测试进行并行单元测试执行

c# - .Net Forms PropertyGrid 在对多个选定对象的属性进行排序时忽略 DisplayNameAttribute

c# - 如何将 SQL 日期转换为 DateTime?

c# - 当我的类多次实现 IEnumerable<T> 时,为什么我不能使用 LINQ to Objects?

c# - 如何获取在方法单元测试中分配给 protected 对象的 HttpContext.Current.Server.MapPath 的假路径?

c# - TransactionScope 未在 MSTest 测试中回滚

c# - Entity Framework 4 仅代码错误 "Multiple objects sets per type are not supported"

python - 如何模拟 os.listdir 以假装 Python 中的文件和目录?

django - 用于在 Django 中进行测试的不同数据库?

android - 我如何模拟和测试这个类?