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; }
代码编译但失败,NullReferenceException
位于DisplayFor
。
任何人都可以帮我做这项工作吗?
(注意:这是一个更大问题的一个简单例子)
答案 0 :(得分:2)
步骤很长,所以我不能写在这里。我在我的博客上写过:D
http://thoai-nguyen.blogspot.com/2011/07/unit-test-displayformat-attribute.html
干杯
答案 1 :(得分:1)
我使用以下代码来测试和验证html助手。
验证是另一个例子。
尝试以下方法:
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);