c# - 将自定义类型用于参数化 MSTest

标签 c# unit-testing testing mstest parameterized-unit-test

我正在创建单元测试,我想使用自定义类型(如 dto)创建参数化测试。

我想做这样的事情:

[TestMethod]
[DataRow(new StudentDto { FirstName = "Leo", Age = 22 })]
[DataRow(new StudentDto { FirstName = "John" })]
public void AddStudent_WithMissingFields_ShouldThrowException(StudentDto studentDto) {
    // logic to call service and do an assertion
}
  1. 这是你能做的事吗?我收到一条错误消息,提示“属性参数必须是常量表达式...”我想我在某处看到属性只能将原始类型作为参数?
  2. 这是错误的方法吗?我应该只传递属性并在测试中创建 dto 吗?

最佳答案

Is this something that you can do? I'm getting an error that says "An Attribute argument must be a constant expression..." I think I saw somewhere that attributes can only take primitive types as arguments?

该消息是正确的。无需进一步解释。

Is this the wrong approach? Should I just pass in the properties and create the dto within the test?

您可以使用原始类型并在测试中创建模型。

[TestMethod]
[DataRow("Leo", 22)]
[DataRow("John", null)]
public void AddStudent_WithMissingFields_ShouldThrowException(string firstName, int? age,) {
    StudentDto studentDto = new StudentDto { 
        FirstName = firstName, 
        Age = age.GetValueOrDefault(0) 
    };
    // logic to call service and do an assertion
}

或者按照评论中的建议,使用[DynamicData] 属性

static IEnumerable<object[]> StudentsData {
    get {
        return [] {
            new object[] {
                new StudentDto { FirstName = "Leo", Age = 22 },
                new StudentDto { FirstName = "John" }
            }
        }
    }
}

[TestMethod]
[DynamicData(nameof(StudentsData))]
public void AddStudent_WithMissingFields_ShouldThrowException(StudentDto studentDto) {
    // logic to call service and do an assertion
}

关于c# - 将自定义类型用于参数化 MSTest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51427032/

相关文章:

c++ - 如何使用 shared_ptr 从外部提供模拟对象?

ruby-on-rails - 使用 Rails 进行敏捷 Web 开发 Book Create Product Test Failure

java - Junit:判断junit是否在运行

c# - 如何读取 appSettings.json 中的字符串数组?

c# - 有没有办法在 C# 代码 (Linq-to-sql) 中获取两点之间检索的所有数据

c# - 创建 Entity Framework 模型时忽略数据库默认值

perl - 测试::简单检查文件是否存在

testing - 如何在 Jmeter 中找到准确的 "Total Testing duration time"?

c# - 需要删除字符串中的xml节点并保留文本

c# - .NET (4.0 - C#) 的可靠加密日志记录?