Regex属性在测试时未引发错误

vlju58qv  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(141)

我正在实现一些集成测试,有一个实体具有某些必须遵守的属性,该实体如下:

[Table("ManualClassifiers")] 
public class ManualClassifier : Classifier
{
    [RegularExpression(@"^([a-zA-Z]+?)([-\s'][a-zA-Z]+)*?")]
    [Required(ErrorMessage = "First name field is mandatory")]
    [Column(name: "first_name")]
    public string FirstName { get; set; }
    [RegularExpression(@"^([a-zA-Z]+?)([-\s'][a-zA-Z]+)*?")]
    [Required(ErrorMessage = "Last name field is mandatory")]
    [Column(name: "last_name")]
    public string LastName { get; set; }
    [EmailAddress]
    [Required(ErrorMessage = "Email field is mandatory")]
    [Column(name: "email")]
    public string Email { get; set; }
    [RegularExpression(@"^[a-zA-Z0-9._]+$")]
    [Required(ErrorMessage = "Username field is mandatory")]
    [Column(name: "username")]
    public string Username { get; set; }
    [Required(ErrorMessage = "Password hash field is mandatory")]
    [Column(name: "passwordHash")]
    public string PasswordHash { get; set; }
    [Required(ErrorMessage = "Password salt field is mandatory")]
    [Column(name: "passwordSalt")]
    public string PasswordSalt { get; set; }
}

当尝试验证第一个正则表达式时,我的测试总是通过(即使我的输入是一白色,因此应该失败或抛出一些错误)。

[TestMethod]
    public async Task Insert_ManualClassifier_With_Empty_Field_Fails()
    {
        using var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        var options = new DbContextOptionsBuilder<DataContext>()
            .UseSqlite(connection) // Set the connection explicitly, so it won't be closed automatically by EF
            .Options;

        // Create the dabase schema
        // MigrateAsync if using Migrations
        using (var context = new DataContext(options))
        {
            await context.Database.EnsureCreatedAsync();
        } // The connection is not closed, so the database still exists

        using (var context = new DataContext(options))
        {
            var user = new ManualClassifier()
            {
                FirstName = "   ", //this is where it should not match the regular expression and fail
                LastName = "Last",
                Email = "example@gmail.com",
                Username = "firstlast123"
            };

            IRepositoryService repoService = new RepositoryService(context, NullLogger<RepositoryService>.Instance);

            string passwordHash = "pwhash";
            string passwordSalt = "pwsalt";

            int userID = await repoService.CreateUser(user, passwordHash, passwordSalt);
        }
    }

这是我正在调用的存储库方法:

public async Task<int> CreateUser(ManualClassifier user, string passwordHash, string passwordSalt)
    {
        //TO DO: CREATE UPPER LAYER IN REPO PROJECT TO MAP RESULTS
        if (_context.ManualClassifiers.Any(u => u.Username == user.Username))
        {
            _logger.LogDebug($"User with email {user.Username} already exists");
            throw new UsernameAlreadyExistsException(user.Username);
        }

        if (_context.ManualClassifiers.Any(u => u.Email == user.Email))
        {
            _logger.LogDebug($"User with email {user.Email} already exists");
            throw new EmailAlreadyExistsException(user.Email);
        }

        user.PasswordHash = passwordHash;
        user.PasswordSalt = passwordSalt;
        user.Email = user.Email.ToLower();

        _logger.LogDebug("New user created successfully");
        await _context.ManualClassifiers.AddAsync(user);
        await _context.SaveChangesAsync();

        return user.Id;
    }
mum43rcc

mum43rcc1#

FirstNameLastName的正则表达式验证缺少字符串锚$。应将$定位点添加到这两个字段的正则表达式验证中。

[Table("ManualClassifiers")] 
public class ManualClassifier : Classifier
{
    [RegularExpression(@"^([a-zA-Z]+?)([-\s'][a-zA-Z]+)*?$")]
    [Required(ErrorMessage = "First name field is mandatory")]
    [Column(name: "first_name")]
    public string FirstName { get; set; }
    [RegularExpression(@"^([a-zA-Z]+?)([-\s'][a-zA-Z]+)*?$")]
    [Required(ErrorMessage = "Last name field is mandatory")]
    [Column(name: "last_name")]
    public string LastName { get; set; }
    [EmailAddress]
    [Required(ErrorMessage = "Email field is mandatory")]
    [Column(name: "email")]
    public string Email { get; set; }
    [RegularExpression(@"^[a-zA-Z0-9._]+$")]
    [Required(ErrorMessage = "Username field is mandatory")]
    [Column(name: "username")]
    public string Username { get; set; }
    [Required(ErrorMessage = "Password hash field is mandatory")]
    [Column(name: "passwordHash")]
    public string PasswordHash { get; set; }
    [Required(ErrorMessage = "Password salt field is mandatory")]
    [Column(name: "passwordSalt")]
    public string PasswordSalt { get; set; }
}

相关问题