繁体   English   中英

如何使用 NUnit 对单个 Fluent Validation Rule 进行单元测试?

[英]How to unit test a single Fluent Validation Rule wit NUnit?

我有一个流利的验证器配置,如下所示:

        public class Validator : AbstractValidator<Command>
        {
            public Validator(IDbContext dbContext)
            {
                RuleFor(c => c.PersonId)
                    .EntityExists<Command, Person>(dbContext, nameof(Command.PersonId));

                RuleFor(c => c.ProjectId)
                    .Cascade(CascadeMode.Stop)
                    .EntityExists<Command, Project>(dbContext, nameof(Command.ProjectId))
                    .MustAsync(async (projectId, cancellation) => !(await dbContext.FindAsync<Project>(new object[] { projectId }, cancellation)).IsCompleted)
                    .WithMessage("The project is completed. You may not set the participation of a completed project");

                RuleFor(c => c.StatusId)
                    .EntityExists<Command, Status>(dbContext, nameof(Command.StatusId))

                ...
            }
        }

我想用 NUnit、NSubstitute 和 Fluent Validation Extensions 对第二条规则进行单元测试:

        [Test]
        public void Should_Not_Have_Validation_Error_If_Valid_ProjectId_Is_Supplied()
        {
            _dbContext.EntityExistsAsync<Project>(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(true);
            _validator.ShouldNotHaveValidationErrorFor(command => command.ProjectId, Guid.NewGuid());
        }

由于缺少PersonId ,测试失败。 我正在测试ProjectId的验证规则,但测试包括PersonId的验证规则。 如果我模拟 dbContext 以使 PersonId 规则通过,则测试会因为缺少StatusId而失败,这也是单独定义的验证规则。

如何测试一个单独属性的规则,而不必模拟 model 中所有其他属性的规则?

validate 方法允许您使用选项并指定要检查的属性。 (默认情况下,它包括所有属性的规则)

因此,这是一个示例(此代码将仅验证 StatudId 的规则)

_validator.Validate(command, options => 
{
  options.IncludeProperties(x => x.StatusId);
});

更多详细信息可以在官方网站上找到。 https://docs.fluentvalidation.net/en/latest/start.html#throwing-exceptions

在@Евгений Елисеев 的提示下(谢谢:)我能够编写仅测试单个属性规则的测试扩展:

        public static IEnumerable<ValidationFailure> ShouldHaveValidationErrorForExact<T, TValue>(this IValidator<T> validator,
            Expression<Func<T, TValue>> expression, TValue value) where T : class, new()
        {
            var instanceToValidate = new T();

            var memberAccessor = new MemberAccessor<T, TValue>(expression, true);
            memberAccessor.Set(instanceToValidate, value);

            TestValidationResult<T> testValidationResult = validator.TestValidate(instanceToValidate, opt => opt.IncludeProperties(memberAccessor.Member.Name));
            return testValidationResult.ShouldHaveValidationErrorFor(expression);
        }

        public static IEnumerable<ValidationFailure> ShouldHaveValidationErrorForExact<T, TValue>(this IValidator<T> validator, Expression<Func<T, TValue>> expression, T objectToTest) where T : class
        {
            TValue value = expression.Compile()(objectToTest);
            var memberAccessor = new MemberAccessor<T, TValue>(expression, true);
            TestValidationResult<T> testValidationResult = validator.TestValidate(objectToTest, opt => opt.IncludeProperties(memberAccessor.Member.Name));
            return testValidationResult.ShouldHaveValidationErrorFor(expression);
        }

        public static void ShouldNotHaveValidationErrorForExact<T, TValue>(this IValidator<T> validator,
            Expression<Func<T, TValue>> expression, TValue value) where T : class, new()
        {

            var instanceToValidate = new T();

            var memberAccessor = new MemberAccessor<T, TValue>(expression, true);
            memberAccessor.Set(instanceToValidate, value);

            TestValidationResult<T> testValidationResult = validator.TestValidate(instanceToValidate, opt => opt.IncludeProperties(memberAccessor.Member.Name));
            testValidationResult.ShouldNotHaveValidationErrorFor(expression);
        }

        public static void ShouldNotHaveValidationErrorForExact<T, TValue>(this IValidator<T> validator, Expression<Func<T, TValue>> expression, T objectToTest) where T : class
        {
            TValue value = expression.Compile()(objectToTest);
            var memberAccessor = new MemberAccessor<T, TValue>(expression, true);
            TestValidationResult<T> testValidationResult = validator.TestValidate(objectToTest, opt => opt.IncludeProperties(memberAccessor.Member.Name));
            testValidationResult.ShouldNotHaveValidationErrorFor(expression);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM