Search code examples
c#unit-testingnunitnunit-3.0

NUnit Throws Constraint how to assert object's value in a list?


my exception class has a List, contain multiple error messages like this:

public class MyExceptions : Exception {
    public List<MyValidationError> ValidationErrors { get; set; }
}
public class MyValidationError {
    public string Name { get; set; }
    public string Description { get; set; }
}

in my unit test, I want to assert my exception object like this:

// MyExceptions throws
{
    ValidationErrors: [
        {Name: "field1", Description: "missing field 1"},
        {Name: "field2", Description: "missing field 2"},
    ]
}

How can I assert the exception contains ValidationErrors with Description "missing field 2"? What I am trying to do like this (but failed)

Assert.That(
    () => {
        // do something, throw MyExceptions as above
    },
    Throws.TypeOf<MyExceptions>().And
        .With.Property("ValidationErrors")
        .Has.One.With.Property("Description").EqualTo("missing field 2")
    );

Solution

  • For the sake of clarity, I would split the assertion that a specific exception has been thrown from the assertions of its properties:

    var exception = Assert.Throws<MyExceptions>(() => {
                // do something, throw MyExceptions as above
            }); 
    
    Assert.That(exception.ValidationErrors.Count, Is.EqualTo(2));
    Assert.That(exception.ValidationErrors[0].Name, Is.EqualTo("field 1"));
    // etc