Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asserting that a system under test should throw an assertion exception

I am creating an extension method that performs a test on an object to see if it has a specific custom attribute.

I want to create a unit test for my extension method. How can I assert that the test in the extension method should fail?

[Test]
public void ShouldFailIfEmailAttributeMissingFromFieldName()
{
    //--Arrange
    var model = new { Field = 1 };

    //--Act
    model.ShouldValidateTheseFields(new List<FieldValidation>
    {
        new EmailAddressFieldValidation
        {
            ErrorId = 1,
            ErrorMessage = "Message",
            FieldName = nameof(model.Field)
        }
    });
    //--Assert

}

Basically, the ShouldValidateTheseFields does reflection and asserts that it should have a custom attribute on the field named "Field" and I need to assert that it failed.

like image 781
Nick Gallimore Avatar asked Jun 07 '18 18:06

Nick Gallimore


1 Answers

Catch the expected exception. If none is thrown the test fails

[Test]
public void ShouldFailIfEmailAttributeMissingFromFieldName() {
    //--Arrange
    var model = new { Field = 1 };

    //--Act
    try {
        model.ShouldValidateTheseFields(new List<FieldValidation> {
            new EmailAddressFieldValidation {
                ErrorId = 1,
                ErrorMessage = "Message",
                FieldName = nameof(model.Field)
            }
        });
    } catch(MyExpectedException e) {
        return;
    }

    //--Assert
    Assert.Fail();
}

Depending on the test framework being used there should be a way for you to assert expected exceptions for a test, which would basically follow a similar format above under the hood.

like image 60
Nkosi Avatar answered Oct 08 '22 10:10

Nkosi