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
202 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
72 0
|
XML SQL 数据库
Error getting generated key or setting result to parameter object.必须执行该语句才能获得结果。
Error getting generated key or setting result to parameter object.必须执行该语句才能获得结果。
2711 47
|
3月前
引用 AspNetCoreRateLimit => StatusCode cannot be set because the response has already started.
引用 AspNetCoreRateLimit => StatusCode cannot be set because the response has already started.
58 0
|
4月前
|
前端开发 Java Spring
为什么会出现Request method ‘GET‘ not supported`
为什么会出现Request method ‘GET‘ not supported`
690 1
|
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“:“/*
231 0
|
JSON 数据格式
Required request parameter ‘name‘ for method parameter type String is not present 报错解决方法
Required request parameter ‘name‘ for method parameter type String is not present 报错解决方法
3692 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
174 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
546 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