Leo Reyes
Leo Reyes

Reputation: 101

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?

Upvotes: 3

Views: 2619

Answers (1)

Nkosi
Nkosi

Reputation: 247078

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
}

Upvotes: 3

Related Questions