Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

TryValidateModel in unit tests

$
0
0

Hi! :)

I am trying to unit test an action which invokes TryValidateModel but it throws errors all the time and I can't figure out how to make it work (after searching through the code of MVC 6). I am using beta8.

Here are some small examples to illustrate the problem:

Controller:

    public class HomeController : Controller
    {
        [HttpPost]
        public IActionResult Index(SomeModel model)
        {
            this.TryValidateModel(model);

            if (this.ModelState.IsValid)
            {
                return Ok();
            }

            return HttpBadRequest();
        }
    }

Model:

    public class SomeModel
    {
        [Required]
        public int Int { get; set; }

        [Required]
        [StringLength(20, MinimumLength = 5)]
        public string String { get; set; }
    }

Unit test class (with copied code from MVC source tests)

public class ControllersTest
    {
        [Fact]
        public void TryValidateModelTest()
        {
            var controller = GetController(new GenericModelBinder(), new CompositeValueProvider());

            controller.Index(new SomeModel()); // throws exception, test fails

            Assert.False(controller.ModelState.IsValid);
        }

// code copied from MVC source unit tests but still throws exception private static HomeController GetController(IModelBinder binder, IValueProvider provider) { var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); var httpContext = new DefaultHttpContext(); var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var viewData = new ViewDataDictionary(metadataProvider, new ModelStateDictionary()); var tempData = new TempDataDictionary(new HttpContextAccessor(), new SessionStateTempDataProvider()); var bindingContext = new ActionBindingContext() { ModelBinder = binder, ValueProvider = provider, InputFormatters = new List<IInputFormatter>(), ValidatorProvider = new DataAnnotationsModelValidatorProvider( options: null, stringLocalizerFactory: null) }; var contr = new HomeController() { ActionContext = actionContext, BindingContext = bindingContext, MetadataProvider = metadataProvider, ViewData = viewData, TempData = tempData, ObjectValidator = new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], metadataProvider) }; return contr; } }

Full example is available here: LINK

Any suggestions or pointers how to make it work?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>