单元测试中的模型状态验证
本文关键字:状态 验证 模型 单元测试 | 更新日期: 2023-09-27 18:20:05
我正在为这样的控制器编写一个单元测试:
public HttpResponseMessage PostLogin(LoginModel model)
{
if (!ModelState.IsValid)
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
模型看起来像:
public class LoginModel
{
[Required]
public string Username { set; get; }
[Required]
public string Password { set; get; }
}
然后我有这样的单元测试:
[TestMethod]
public void TestLogin_InvalidModel()
{
AccountController controller = CreateAccountController();
...
var response = controller.PostLogin(new LoginModel() { });
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
}
实际上ModelState已经过验证。。。这对我来说很奇怪,因为这两个字段都是必需的。。。有人能提出建议吗?
TL;DR如果你不想阅读Youssef提供的整篇文章,并且想要一个如何使ModelState.IsValid返回false的快速解决方案。这样做。
[TestMethod]
public void TestLogin_InvalidModel()
{
AccountController controller = CreateAccountController();
// new code added -->
controller.ModelState.AddModelError("fakeError", "fakeError");
// end of new code
...
var response = controller.PostLogin(new LoginModel() { });
Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
}
现在我可以想象CreateAccountController()对于minimum->是这样的
return new AccountApiController()
{
Request = new HttpRequestMessage(),
Configuration = new HttpConfiguration()
};
希望这能给那些在谷歌上搜索的人一个快速的答案:)
模型状态有效的原因是在新建控制器时会创建一个新的模型状态。Web API在这里没有为您进行参数绑定,因此它甚至没有机会添加模型状态错误。
如果你想把它作为一个单元测试,那么你应该自己添加模型状态错误,并测试会发生什么。
如果你想测试模型状态在实际请求中是否无效,我建议你阅读以下博客文章:
http://blogs.msdn.com/b/youssefm/archive/2013/01/28/writing-tests-for-an-asp-net-webapi-service.aspx
并尝试针对内存中的服务器进行测试。对于您的情况,需要注意的一点是,您可能希望在请求中使用StringContent而不是ObjectContent,以确保Web API尝试正确地反序列化和绑定主体。
如前所述,您需要集成测试来验证ModelState。因此,对于Asp.Net Core,我正在挖掘这个问题,以添加一个简单的解决方案,用于将测试与Asp.Net核心集成,并验证ModelState
添加包Microsoft.AspNetCore.TestHost
,您可以通过以下简单方式提交请求:
var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
var client = server.CreateClient();
var model = new { Name = String.Empty };
var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var result = await client.PostAsync("/api/yourApiEndpoint", content);
result.StatusCode.Should().Be(HttpStatusCode.BadRequest);
你可以在这里找到更多关于它的信息:http://asp.net-hacker.rocks/2017/09/27/testing-aspnetcore.html
希望能有所帮助。
我在单元测试Visual studio 2017,C#,NET 4.x.x 中使用了以下内容来验证模型状态
[TestMethod]
public void TestYourValidationModel()
{
var configuration = new HttpConfiguration();
configuration.Filters.Add(new ValidateModelAttribute());
// Get the quote
var controller = new YourController
{
Request = new HttpRequestMessage(),
Configuration = configuration
};
var request = YourRequestObject;
controller.Request.Content = new ObjectContent<YourRequestType>(
request, new JsonMediaTypeFormatter(), "application/json");
controller.Validate(request);
Assert.IsTrue(controller.ModelState.IsValid, "This must be valid");
}
示例是针对JSON格式的请求。将YourController替换为控制器的名称,将YourRequestType替换为请求的对象类型。
这使您可以选择在不使用服务的情况下测试模型进行验证。
我无法得到响应。响应对象的StatusCode属性。所以我不得不断言如下,这对我来说很好
IHttpActionResult actionResult=控制器。ActionMethod(请求);
Assert.IsIInstanceOf(actionResult);
有没有办法检查响应对象上的状态代码?比如。Assert.AreEqual(HttpStatusCode.BadRequest,response.StatusCode);