在VS 2015中使用MVC 5上的Web应用程序。
这是我的模特:
public class InfoFormulaireEmployeModele
{
[Required(ErrorMessage =" *You must provide a date")]
[RegularExpression("^[0-9]{8}$", ErrorMessage ="The date must be of the format AAAAMMJJ")]
public string dateEvenementInitial { get; set; }
}
当我尝试输入一些无效的输入时,让我们说“12ab' ,它运行正常,我回到页面上并显示错误消息。
以下是我的观点:
@using PortailLibreService.Models
@model InfoFormulaireEmployeModele
@{
ViewBag.Title = "ChampsFormulaireInvalidite";
}
@using (Html.BeginForm())
{
<div class="editor-field">
<b>Initial event </b><br>
<p>When did the initial event occured?</p>
@Html.TextBoxFor(x => x.dateEvenementInitial, new { @placeholder = "AAAAMMJJ" }) @Html.ValidationMessageFor(x => x.dateEvenementInitial, null, new { @class = "error" })
</div>
<input type="submit" name="Save" value="Submit" />
}
我想创建一个单元测试,以确保我的模型对于无效的日期条目无效。
这是我的单元测试:
[TestMethod]
public void testRetourPossibleInvalide()
{
InfoFormulaireEmployeModele modelDuplicat = new InfoFormulaireEmployeModele();
modelDuplicat.dateEvenementInitial = "abc";
InvFormController controlleur = lib.getController("100237");
var result = controlleur.ChampsFormulaireInvalidite(modelDuplicat);
Assert.AreEqual(false, controlleur.ModelState.IsValid);
}
由于某种原因,测试失败,controlleur.ModelState.IsValid为true,而它应为false。如果我只用数值测试它就可以了。例如,这个测试通过了:
[TestMethod]
public void testRetourPossibleInvalide()
{
InfoFormulaireEmployeModele modelDuplicat = new InfoFormulaireEmployeModele();
modelDuplicat.dateRetourPossible = "129";
InvFormController controlleur = lib.getController("100237");
var result = controlleur.ChampsFormulaireInvalidite(modelDuplicat);
Assert.AreEqual(false, controlleur.ModelState.IsValid);
}
运行测试时controlleur.ModelState.IsValid为false,因此测试通过。
我试图在我的控制器方法中放置一个断点,但在调试时我无法达到它。
答案 0 :(得分:0)
您必须充当框架,通常会为您完成所有检查。
[TestMethod]
public void testRetourPossibleInvalide() {
var model = new InfoFormulaireEmployeModele();
model.dateEvenementInitial = "abc";
var controller = new InvFormController();
var bindingContext = new ModelBindingContext() {
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
};
var boundModel = new DefaultModelBinder().BindModel(new ControllerContext(), bindingContext);
controller.ModelState.Clear();
controller.ModelState.Merge(bindingContext.ModelState);
var result = controller.ChampsFormulaireInvalidite(model);
Assert.AreEqual(false, controller.ModelState.IsValid);
}