DisplayFormat unit testing with HtmlHelper
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));
I want to test that the output produced by calling DisplayFor
is in the format specif开发者_StackOverflow社区ied by...
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}")]
public DateTime? PriceDate { get; set; }
The code compiles but fails with a NullReferenceException
at DisplayFor
.
Can anyone help me make this work?
(Note: This is a trivial example of a larger problem)
The steps are quite long so I couldn't write here. I wrote about it at my blog :D
http://thoai-nguyen.blogspot.com/2011/07/unit-test-displayformat-attribute.html
Cheers
I use the following code to test and validate html helpers.
Validation is a another example.
Try the following:
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);
精彩评论