使用HtmlHelper进行DisplayFormat单元测试
本文关键字:单元测试 DisplayFormat 进行 HtmlHelper 使用 | 更新日期: 2023-09-27 18:02:56
MyModel _model = new MyModel() { PriceDate = new DateTime(2000, 1, 1)};
var helper = new System.Web.Mvc.HtmlHelper<MyModel>(new ViewContext(), new ViewPage());
var result = helper.DisplayFor(m => _model.PriceDate);
Assert.That(result, Is.EqualTo(expected));
我想测试调用DisplayFor
所产生的输出的格式是否为…
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}")]
public DateTime? PriceDate { get; set; }
代码可以编译,但在DisplayFor
处NullReferenceException
失败。
(注意:这是一个比较大的问题的小例子)
步骤很长,所以我不能在这里写。我把它写在我的博客上:D
http://thoai-nguyen.blogspot.com/2011/07/unit-test-displayformat-attribute.html欢呼
我使用以下代码来测试和验证html帮助程序。
Validation是另一个例子。
尝试以下操作:
var sb = new StringBuilder();
var context = new ViewContext();
context.ViewData = new ViewDataDictionary(_testModel);
context.Writer = new StringWriter(sb);
var page = new ViewPage<TestModel>();
var helper = new HtmlHelper<TestModel>(context, page);
//Do your stuff here to exercise your helper
//Following example contains two helpers that are being tested
//A MyCustomBeginForm Helper and a OtherCoolHelperIMade Helper
using(helper.MyCustomBeginForm("secretSauce"))
{
helper.ViewContext.Writer.WriteLine(helper.OtherCoolHelperIMade("bigMacSauce"));
}
//End Example
//Get the results of all helpers
var result = sb.ToString();
//Asserts and string tests here for emitted HTML
Assert.IsNotNullOrEmpty(result);