猿问

断言被测系统应该抛出断言异常

我正在创建一个扩展方法,该方法对对象执行测试以查看它是否具有特定的自定义属性。


我想为我的扩展方法创建一个单元测试。如何断言扩展方法中的测试应该失败?


[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


}

基本上,ShouldValidateTheseFieldsdoes 反射并断言它应该在名为“Field”的字段上有一个自定义属性,我需要断言它失败了。


慕村225694
浏览 176回答 2
2回答

白衣非少年

创建一个新的自定义异常并在缺少自定义属性时抛出它:&nbsp; &nbsp; [Test]&nbsp; &nbsp; public void ShouldFailIfEmailAddressAttributeIsMissingFromFieldName()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //--Arrange&nbsp; &nbsp; &nbsp; &nbsp; var model = new { Field = 1 };&nbsp; &nbsp; &nbsp; &nbsp; //--Act&nbsp; &nbsp; &nbsp; &nbsp; Should.Throw<EmailAddressAttributeNotFoundException>(() => model.ShouldValidateTheseFields(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new List<FieldValidation>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new EmailAddressFieldValidation&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ErrorId = 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ErrorMessage = "Message",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FieldName = nameof(model.Field)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }));&nbsp; &nbsp; }要检查断言是否失败,您需要捕获断言异常。在这种情况下,由于使用了 Shouldly 框架,因此在扩展方法中抛出了一个 Shouldly.ShouldAssertException:[Test]public void ShouldFailIfEmailAddressAttributeHasWrongErrorId(){&nbsp; &nbsp; //--Arrange&nbsp; &nbsp; var model = new TestModelTwo();&nbsp; &nbsp; //--Act&nbsp; &nbsp; Should.Throw<ShouldAssertException>(() => model.ShouldValidateTheseFields(&nbsp; &nbsp; new List<FieldValidation>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; new EmailAddressFieldValidation&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ErrorId = 2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ErrorMessage = "Message",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FieldName = nameof(model.Field)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }));}使用类:public class TestModel{&nbsp; &nbsp; [EmailAddress(1)]&nbsp; &nbsp; public string Field { get; set; }}扩展方法中的失败断言是 ErrorId.ShouldBe(2) 当它在模型上实际上是 1 时。
随时随地看视频慕课网APP
我要回答