0

我想AbstractValidator<T>在基实体类中使用。

[Serializable]
public abstract class Entity<T> where T : Entity<T>
{
    public virtual Boolean Validate(AbstractValidator<T> validator)
    {
        return validator.Validate(this as ValidationContext<T>).IsValid;
    }
    // other stuff..
}

但是我的一个测试失败了,说该Validate()方法不能接受null作为参数。

[Test]
public void CategoryDescriptionIsEmpty()
{
    var category = new Category
    {
        Title = "some title",
        Description = String.Empty
    };

    Assert.False(category.Validate(this.validator) == true);
}

[SetUp]
public void Setup()
{
    this.validator = new CategoryValidator();
}

我正在使用Visual Web Developer,目前无法安装C# Developer Express以创建控制台应用程序来调试错误。既然我不知道如何在单元测试中调试。或者,如果可以给出一些解释,那就太好了!

谢谢!

4

2 回答 2

2

这个话题很老,但我发现很有用并且有所不同:

public abstract class WithValidation<V> where V : IValidator
    {

        private IValidator v = Activator.CreateInstance<V>();

        public bool IsValid => !(Errors.Count() > 0);

        public IEnumerable<string> Errors
        {
            get
            {
                var results = v.Validate(this);

                List<string> err = new List<string>();

                if (!results.IsValid)
                    foreach (var item in results.Errors)
                        err.Add(item.ErrorMessage);

                return err;

            }
        }
    }

public class Client : WithValidation<ClientValidator>
    {

        public Guid Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

    }

public class ClientValidator : AbstractValidator<Client>
    {

        public ClientValidator()
        {
            RuleFor(c => c.Name).NotNull();
            RuleFor(c => c.Age).GreaterThan(10);
        }


    }

因此,您现在可以更轻松地使用,例如:

Client c = new Client();

var isvalid = c.IsValid;

IList<string> errors = c.Errors;
于 2018-09-24T01:27:37.380 回答
0

好的!

所以接下来是我的问题的解决方案(至少这可以按预期工作):

public abstract class Entity<T> where T : Entity<T>
{
    public Boolean IsValid(IValidator<T> validator)
    {
        // var context  = new ValidationContext(this);
        // var instance = context.InstanceToValidate as T;
        // return validator.Validate(instance).IsValid;

        return validator.Validate(this as T).IsValid;
    }
}
public class Rambo : Entity<Rambo>
{
    public Int32 MadnessRatio { get; set; }
    public Boolean CanHarmEverything { get; set; }
}   
public class RamboValidator : AbstractValidator<Rambo>
{
    public RamboValidator()
    {
        RuleFor(r => r.MadnessRatio).GreaterThan(100);
    }
}

class Program
{
    public static void Main(String[] args)
    {
        var ramboInstance = new Rambo {
            MadnessRatio = 90
        };          

        Console.WriteLine("Is Rembo still mad?");
        Console.WriteLine(ramboInstance.IsValid(new RamboValidator()));

        Console.ReadKey();
    }
}
于 2011-12-30T11:06:24.833 回答