ASP.NET MVC Controller post method unit test: ModelState.IsValid always true

前端 未结 2 440
南笙
南笙 2020-12-12 17:36

I have written my first unit tests for an ASP.NET MVC web application. All works fine and it is giving me valuable information, but I can\'t test errors in the view model. T

2条回答
  •  星月不相逢
    2020-12-12 18:01

    I found this solution: SO: Validation does not work when I use Validator.TryValidateObject combined with the solution @Kenneth provided:

    [TestMethod]
        public void test_validation()
        {
            var sut = new POSViewModel();
            // Set some properties here
            var context = new ValidationContext(sut, null, null);
            var results = new List();
            TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(POSViewModel), typeof(POSViewModel)), typeof(POSViewModel));
    
            var isModelStateValid = Validator.TryValidateObject(sut, context, results, true);
    
            // Assert here
        }
    

    If you have a class library with all you resources in, don't forget to reference it in your test project.

提交回复
热议问题