我有以下单元测试:
[TestMethod]
public void GivenInvalidUrlExpectInvalidModelState()
{
//Arrange
HomeController homeController = new HomeController();
InputFields inputFields = new InputFields { Url = "google.com/", KeyWords = "some key words" };
//Act
ViewResult actionResult = homeController.GetResults(inputFields);
//Assert
Assert.IsFalse(actionResult.ViewData.ModelState.IsValid);
}
以下型号:
public class InputFields
{
[Url]
[Required(ErrorMessage="Please provide a URL")]
public string Url { get; set; }
[Required(ErrorMessage="Please provide key words")]
public string KeyWords { get; set; }
}
当我使用无效网址(没有协议)从用户界面点击控制器时,google.com/
ModelState
按预期为假。
然而,在单元测试中,ModelState
为真。
为什么模型没有在单元测试中验证?
答案 0 :(得分:3)
这些验证属性在运行时通过管道由asp.net mvc框架进行评估。在进行单元测试时,没有管道,所以某些期望不适用。
你必须自己操纵这个州
[TestMethod]
public void GivenInvalidUrlExpectInvalidModelState() {
//Arrange
var homeController = new HomeController();
//manually adding error that would cause `ModelState.IsValid` to be false
homeController.ModelState.AddModelError("Url", "invalid data");
var inputFields = new InputFields { Url = "google.com/", KeyWords = "some key words" };
//Act
ViewResult actionResult = homeController.GetResults(inputFields);
//Assert
Assert.IsFalse(actionResult.ViewData.ModelState.IsValid);
}
为了测试管道中的模型状态,您可能需要运行端到端集成测试,其中向控制器发出HTTP请求