C#单元测试用于测试Dto属性的属性

时间:2017-12-07 11:22:08

标签: c# asp.net-mvc unit-testing attributes mocking

我跟随Dto使用一些属性来验证属性。当我传递一些无效的属性值时,我的单元测试允许这些值而不根据给定的属性条件进行验证。我是第一次这样做,所以我没有想法实现它。

public class UserDto : IModelWithId
{
    public int Id { get; set; }
    [MinLength(1, ErrorMessageResourceName = "Error_User_UsernameMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_UsernameMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [RegularExpression(@"^[A-Za-z0-9äöüÄÖÜß]+(?:[._-][A-Za-z0-9äöüÄÖÜß]+)*$", ErrorMessageResourceName = "Error_User_UsernameFormat", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string UserName { get; set; }        

    [MinLength(1, ErrorMessageResourceName = "Error_User_NameMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_NameMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string Name { get; set; }

    [MinLength(1, ErrorMessageResourceName = "Error_User_EmailMinLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [MaxLength(255, ErrorMessageResourceName = "Error_User_EmailMaxLength", ErrorMessageResourceType = typeof(Properties.Resources))]
    [EmailAddress(ErrorMessageResourceName = "Error_User_EmailAddress", ErrorMessageResourceType = typeof(Properties.Resources))]
    public string Email { get; set; }
}

1 个答案:

答案 0 :(得分:2)

您可以使用验证程序类来验证您的dto:

life_time

或者像这样没有例外:

var dto = new UserDto();
dto.Email = "not an email";
var ctx = new System.ComponentModel.DataAnnotations.ValidationContext(dto);
// will throw an exception if invalid
System.ComponentModel.DataAnnotations.Validator.ValidateObject(dto, ctx, true);