2 回答
TA贡献1155条经验 获得超0个赞
创建一个新的自定义异常并在缺少自定义属性时抛出它:
[Test]
public void ShouldFailIfEmailAddressAttributeIsMissingFromFieldName()
{
//--Arrange
var model = new { Field = 1 };
//--Act
Should.Throw<EmailAddressAttributeNotFoundException>(() => model.ShouldValidateTheseFields(
new List<FieldValidation>
{
new EmailAddressFieldValidation
{
ErrorId = 1,
ErrorMessage = "Message",
FieldName = nameof(model.Field)
}
}));
}
要检查断言是否失败,您需要捕获断言异常。在这种情况下,由于使用了 Shouldly 框架,因此在扩展方法中抛出了一个 Shouldly.ShouldAssertException:
[Test]
public void ShouldFailIfEmailAddressAttributeHasWrongErrorId()
{
//--Arrange
var model = new TestModelTwo();
//--Act
Should.Throw<ShouldAssertException>(() => model.ShouldValidateTheseFields(
new List<FieldValidation>
{
new EmailAddressFieldValidation
{
ErrorId = 2,
ErrorMessage = "Message",
FieldName = nameof(model.Field)
}
}));
}
使用类:
public class TestModel
{
[EmailAddress(1)]
public string Field { get; set; }
}
扩展方法中的失败断言是 ErrorId.ShouldBe(2) 当它在模型上实际上是 1 时。
- 2 回答
- 0 关注
- 167 浏览
添加回答
举报