3

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?
Leo Reyes
  • 101
  • 3
  • We had a similar question a few days ago. You can use DataRow only for constants. For your case use DynamicData instead. See [here](https://stackoverflow.com/questions/51345370/unit-testing-sending-complex-object-as-a-input-parameter-to-my-test-method-usin). – gdir Jul 19 '18 at 15:58
  • @Nkosi yea I think this is a duplicate to what gdir linked. Thanks! – Leo Reyes Jul 19 '18 at 16:04

1 Answers1

3

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
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472