ivaylokenov / MyTested.AspNetCore.Mvc

Fluent testing library for ASP.NET Core MVC.
https://docs.mytestedasp.net/
Other
1.73k stars 175 forks source link

Fluent validations on model class #372

Closed gkfischer closed 4 years ago

gkfischer commented 4 years ago

All my validations on model classes are defined as fluent validations in OnModelCreating of the DataContext and not as attributes on the properties of the models, like so:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
          modelBuilder.ApplyConfiguration(new ServiceConfiguration());
    }
    public class ServiceConfiguration : IEntityTypeConfiguration<Service>
    {
        public void Configure(EntityTypeBuilder<Service> builder)
        {
            builder
                .Property(b => b.Name).IsRequired().HasMaxLength(250);
            builder
                .Property(b => b.ProductOwner).IsRequired().HasMaxLength(250);
            ...
        }
    }

But these validation rules are not loaded as it seems when the test framework runs as the ModelState collection doesn't contain any entries. How can I get the framework to load them?

ivaylokenov commented 4 years ago

These are database configurations, and not fluent validations. Does your web application register them in the ModelState, when you try to make a normal web request?

gkfischer commented 4 years ago

Nothing special done to register them, it's just an alternative way to specify restrictions on properties, like described here: https://docs.microsoft.com/en-us/ef/core/modeling/. When running the app these are added as validations to the ModelState.

ivaylokenov commented 4 years ago

I will take a look. Maybe it is some sort of misconfiguration on the library's end.

gkfischer commented 4 years ago

Thanks

ivaylokenov commented 4 years ago

I am not quite sure about this because I tried to reproduce it and the ModelState does not consider the IEntityTypeConfiguration fluent validation as I expected and it stays valid. These interface and configuration are database related. If you ModelState shows errors, you are configuring validation from somewhere else. I am attaching a solution, in which I am trying to reproduce your issue but cannot. Could you send me a solution sample of some sort so that I can take a look?

TestFluentValidation.zip

gkfischer commented 4 years ago

I can do that over the weekend. Time's running out today

ivaylokenov commented 4 years ago

@gkfischer No worries, I will leave the issue open. Waiting for your input and will assist you as soon as possible. Thank you!

gkfischer commented 4 years ago

Ok, to make a long story short: my mistake. The fluent validations are only used by EF but not by the MVC framework. Strange design, as the DataAnnotations on the properties are used by both. But anyway, everythings fine when adding something like https://docs.fluentvalidation.net/en/latest/index.html.