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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With