相关疑难解决方法(0)

单元测试HtmlHelper扩展方法失败

我正在尝试测试HtmlHelper我编写的一些扩展方法.我的第一个问题是如何创建一个HtmlHelper实例,但我使用这个代码解决了这个问题:

private static HtmlHelper<T> CreateHtmlHelper<T>(T model)
{
    var viewDataDictionary = new ViewDataDictionary(model);
    var controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object,
    new RouteData(),
    new Mock<ControllerBase>().Object);

    var viewContext = new ViewContext(controllerContext, new Mock<IView>().Object, viewDataDictionary, new TempDataDictionary(), new Mock<TextWriter>().Object);

    var mockViewDataContainer = new Mock<IViewDataContainer>();
mockViewDataContainer.Setup(v => v.ViewData).Returns(viewDataDictionary);

    return new HtmlHelper<T>(viewContext, mockViewDataContainer.Object);
}
Run Code Online (Sandbox Code Playgroud)

我的几个测试现在工作正常,但有一个测试会引发异常.测试定义如下:

// Arrange
var inputDictionary = CreateDictionary();
var htmlHelper = CreateHtmlHelper(inputDictionary);

// Act
var actualHtmlString = htmlHelper.EditorFor(m => m.Dict, model).ToHtmlString();
...
Run Code Online (Sandbox Code Playgroud)

EditorFor方法是我的扩展方法.在该方法的某处,进行以下调用:

tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(expression, metadata));    
Run Code Online (Sandbox Code Playgroud)

从我的单元测试执行此代码时,抛出以下异常:

System.NullReferenceExceptionObject reference …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc unit-testing html-helper

9
推荐指数
1
解决办法
2786
查看次数

单元使用AutoFixture测试Html Helper

我正在尝试使用AutoFixture对Html Helper进行单元测试.以下是我的SUT

public static MvcHtmlString SampleTable(this HtmlHelper helper,
    SampleModel model, IDictionary<string, object> htmlAttributes)
{
    if (helper == null)
    {
        throw new ArgumentNullException("helper");
    }
    if (model == null)
    {
        throw new ArgumentNullException("model");
    }

    TagBuilder tagBuilder = new TagBuilder("table");
    tagBuilder.MergeAttributes(htmlAttributes);
    tagBuilder.GenerateId(helper.ViewContext.HttpContext.Items[Keys.SomeKey].ToString());
    return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它只返回一个带有表标签的MVC Html字符串,并附加了Id.(参见下面的单元测试结果示例)

使用AutoFixture进行单元测试:

[Fact]
public void SampleTableHtmlHelper_WhenKeyExistWithinHttpContext_ReturnsExpectedHtml()
{
    var fixture = new Fixture();

    //Arrange
    fixture.Inject<HttpContextBase>(new FakeHttpContext());
    var httpContext = fixture.CreateAnonymous<HttpContextBase>();
    fixture.Inject<ViewContext>(new ViewContext());
    var vc = fixture.CreateAnonymous<ViewContext>();

    vc.HttpContext = httpContext;
    vc.HttpContext.Items.Add(Keys.SomeKey, "foo");

    fixture.Inject<IViewDataContainer>(new FakeViewDataContainer());
    var htmlHelper = fixture.CreateAnonymous<HtmlHelper>();
    var …
Run Code Online (Sandbox Code Playgroud)

c# model-view-controller unit-testing autofixture

2
推荐指数
1
解决办法
917
查看次数