C# 为参数化MST测试使用自定义类型
我正在创建单元测试,并希望使用自定义类型(如dto)创建参数化测试 我想做这样的事情: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) {
[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
}
[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链接的复制品。谢谢