ModelState.IsValid always returning true while mocking a request

简介: ASB.net  MVC 视图验证里有一个IValidatableObject接口.这里面有一个验证方法.通常我们表单提交的时候dto就是用一个实现IValidatableObject这个接口的实体. 但是在测试的时候,当我们测试控制器的时候会发现控制器里调用ModelState.

ASB.net  MVC 视图验证里有一个IValidatableObject接口.这里面有一个验证方法.通常我们表单提交的时候dto就是用一个实现IValidatableObject这个接口的实体.

但是在测试的时候,当我们测试控制器的时候会发现控制器里调用ModelState.IsValid的时候,永远都是返回true.

这就需要扯到ASB.NET MVC的生命周期了.在这个生命周期里面.模型绑定先于方法调用运行,所以我们在控制器里面调用ModelState.IsValid的时候模型绑定已经完成(这不废话么)

而我们单元测试是直接实例化控制器,然后调用方法的,不走生命周期,所以不会验证视图,IsValid是一个可读的自动属性

 public bool IsValid
    {
      get
      {
        return Enumerable.All<ModelState>((IEnumerable<ModelState>) this.Values, (Func<ModelState, bool>) (modelState => modelState.Errors.Count == 0));
      }
    }

 我们都没有模型绑定,erros.count 当然是0啦,那么ModelState.也就一直都是true了.

 

http://stackoverflow.com/questions/29715295/asp-net-mvc-httpcontext-current-is-null-while-mocking-a-request/29738778#

 

目录
相关文章
|
Serverless
attempt to delete a method
attempt to delete a method
206 1
|
6月前
|
SQL IDE Java
hibernate5 Cannot create TypedQuery for query with more than one return using requested result type
hibernate5 Cannot create TypedQuery for query with more than one return using requested result type
74 0
|
XML SQL 数据库
Error getting generated key or setting result to parameter object.必须执行该语句才能获得结果。
Error getting generated key or setting result to parameter object.必须执行该语句才能获得结果。
2718 47
|
3月前
引用 AspNetCoreRateLimit => StatusCode cannot be set because the response has already started.
引用 AspNetCoreRateLimit => StatusCode cannot be set because the response has already started.
61 0
使用result类一定要添加@Data注解“timestamp“:“2023-09-07T07:57:57.497+00:00““status“: 406,No acceptable repre
使用result类一定要添加@Data注解“timestamp“:“2023-09-07T07:57:57.497+00:00““status“: 406,No acceptable repre
|
12月前
|
PHP
set_error_handler()
set_error_handler()
46 0
|
Java
【Java异常】Feign常见的坑总结之一:Method Not Allowed“,“message“:“Request method ‘POST‘ not supported“,“path“:“/*
【Java异常】Feign常见的坑总结之一:Method Not Allowed“,“message“:“Request method ‘POST‘ not supported“,“path“:“/*
242 0
|
SQL Java 数据库连接
attempted to return null from a method with a primitive return type
attempted to return null from a method with a primitive return type
181 0
|
Java Spring
【feign】Could not write request: no suitable HttpMessageConverter found for request type
【feign】Could not write request: no suitable HttpMessageConverter found for request type
554 0
|
应用服务中间件
returned a response status of 405 Method Not Allowed
returned a response status of 405 Method Not Allowed
returned a response status of 405 Method Not Allowed