我正在创建单元测试,我想使用自定义类型(如 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 吗?
最佳答案
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/