Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为参数化MST测试使用自定义类型_C#_Unit Testing_Testing_Mstest_Parameterized Unit Test - Fatal编程技术网

C# 为参数化MST测试使用自定义类型

C# 为参数化MST测试使用自定义类型,c#,unit-testing,testing,mstest,parameterized-unit-test,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) {

我正在创建单元测试,并希望使用自定义类型(如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
}
  • 这是你能做的吗?我得到了一个错误,说“属性参数必须是常量表达式…”我想我在某个地方看到了属性只能将基元类型作为参数
  • 这是错误的方法吗?我是否应该传入属性并在测试中创建dto
  • 这是你能做的吗?我得到了一个错误,说“属性参数必须是常量表达式…”我想我在某个地方看到了属性只能将基元类型作为参数

    这个信息是正确的。不需要进一步解释

    这是错误的方法吗?我是否应该传入属性并在测试中创建dto

    您可以使用基本类型并在测试中创建模型

    [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
    }
    
    静态IEnumerable StudentsData{
    得到{
    返回[]{
    新对象[]{
    新学生到{FirstName=“Leo”,年龄=22},
    新学生到{FirstName=“John”}
    }
    }
    }
    }
    [测试方法]
    [DynamicData(姓名(学生数据))]
    public void add student_with missing fields_应通过例外项(StudentDto StudentDto){
    //调用服务并执行断言的逻辑
    }
    
    几天前,我们遇到了一个类似的问题。您只能对常量使用DataRow。对于您的情况,请使用dynamicata。看。@Nkosi是的,我认为这是gdir链接的复制品。谢谢