Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using custom types for parameterized MSTests

I'm creating unit tests, and I'm wanting to create parameterized tests using custom types (like a dto).

I'm wanting to do something like this:

[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. 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?
  2. Is this the wrong approach? Should I just pass in the properties and create the dto within the test?
like image 573
Leo Reyes Avatar asked Jul 27 '26 21:07

Leo Reyes


1 Answers

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?

That message is correct. No further explanation needed.

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

You can use the primitive types and create the model 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
}

Or as suggested in the comments, use the [DynamicData] attribute

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
}
like image 98
Nkosi Avatar answered Aug 03 '26 03:08

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!