2

我正在尝试测试自定义 ActionResult 但我没有让它工作。我正在将一个文件写入响应流,所以我想在我的单元测试中做的是读取响应并验证它是否正确。

这是我要测试的方法:

    /// <summary>
    ///     Start writing the file.
    /// </summary>
    /// <param name="response">The response object.</param>
    protected override void WriteFile(HttpResponseBase response)
    {
        // Convert the IList<T> to a datatable.
        dataTable = list.ConvertToDatatable<T>();

        // Add the header and the content type required for this view.
        response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
        response.ContentType = base.ContentType;

        // Gets the current output stream.
        var outputStream = response.OutputStream;

        // Create a new memorystream.
        using (var memoryStream = new MemoryStream())
        {
            WriteDataTable(memoryStream);
            outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }
    }

我已经在单元测试中尝试了以下内容:

        HttpContextBaseMock = new Mock<HttpContextBase>();
        HttpRequestMock = new Mock<HttpRequestBase>();
        HttpResponseMock = new Mock<HttpResponseBase>();
        HttpContextBaseMock.SetupGet(x => x.Request).Returns(HttpRequestMock.Object);
        HttpContextBaseMock.SetupGet(x => x.Response).Returns(HttpResponseMock.Object);

        var routes = new RouteCollection();
        var controller = new CsvActionResultController();
        controller.ControllerContext = new ControllerContext(HttpContextBaseMock.Object, new RouteData(), controller);
        controller.Url = new UrlHelper(new RequestContext(HttpContextBaseMock.Object, new RouteData()), routes);

        var result = controller.ExportToCSV();

但是,我没有让它工作。

如果需要,这里是 CsvActionResult 的完整源代码(没有构造函数):

    /// <summary>
    ///     Start writing the file.
    /// </summary>
    /// <param name="response">The response object.</param>
    protected override void WriteFile(HttpResponseBase response)
    {
        // Add the header and the content type required for this view.
        response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", filename));
        response.ContentType = base.ContentType;

        // Gets the current output stream.
        var outputStream = response.OutputStream;

        // Create a new memorystream.
        using (var memoryStream = new MemoryStream())
        {
            WriteDataTable(memoryStream);
            outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }
    }

    #endregion Methods

    #region Helper Methods

    /// <summary>
    ///     Writes a datatable to a given stream.
    /// </summary>
    /// <param name="stream">The stream to write to.</param>
    private void WriteDataTable(Stream stream)
    {
        var streamWriter = new StreamWriter(stream, encoding);

        // Write the header only if it's indicated to write.
        if (includeRowHeader)
        { WriteHeaderLine(streamWriter); }

        // Move to the next line.
        streamWriter.WriteLine();

        WriteDataLines(streamWriter);

        streamWriter.Flush();
    }

    /// <summary>
    ///     Writes the header to a given stream.
    /// </summary>
    /// <param name="streamWriter">The stream to write to.</param>
    private void WriteHeaderLine(StreamWriter streamWriter)
    {
        foreach (DataColumn dataColumn in dataTable.Columns)
        {
            WriteValue(streamWriter, dataColumn.ColumnName);
        }
    }

    /// <summary>
    ///     Writes the data lines to a given stream.
    /// </summary>
    /// <param name="streamWriter"><The stream to write to./param>
    private void WriteDataLines(StreamWriter streamWriter)
    {
        // Loop over all the rows.
        foreach (DataRow dataRow in dataTable.Rows)
        {
            // Loop over all the colums and write the value.
            foreach (DataColumn dataColumn in dataTable.Columns)
            { WriteValue(streamWriter, dataRow[dataColumn.ColumnName].ToString()); }
            streamWriter.WriteLine();
        }
    }

    /// <summary>
    ///     Write a specific value to a given stream.
    /// </summary>
    /// <param name="writer">The stream to write to.</param>
    /// <param name="value">The value to write.</param>
    private void WriteValue(StreamWriter writer, String value)
    {
        writer.Write(value);
        writer.Write(delimeter);
    }

有人可以指出我正确的方向吗?我是嘲笑的新手。

亲切的问候,

4

1 回答 1

2

就个人而言,我不会走这条路来确保您的网络响应包含适当的结果,尤其是在单元测试场景中。如果您希望通过真正的 Web 交互进行全功能测试(即包含填充有正确值的所有相关属性),我会使用验收测试/UI 测试来确保您具有文件导出的正确行为。

但是,单元测试仍然很重要,因为您希望单独验证事物并确保您获得有关您实施的行为的快速反馈。知道您在单元测试期间没有完整的 ASP.NET 运行时执行,编写这些单元测试的方式略有不同。

所以关于你的评论

例如: Response.OutputStream 始终为空。Response.ContentStream 为空。

请注意,仅存根 HttpContextBase、HttpResponseBase 并将其分配给 ControllerContext,并不意味着它将具有所有必要的属性,例如在单元测试执行上下文期间设置的 OutputStream、ContentStream、响应标头、内容类型。您正在处理 Moq.Mock 提供的代理/模拟/存根对象(即 HttpResponseMock ),因此您无法像在正常执行 ASP.NET web 期间通常获得的那样获得这些属性。这就是为什么在单元测试执行上下文期间,您会看到这些属性返回 null。

您可以使这些属性不返回 null。您可以像通常对其他虚拟属性所做的那样对这些属性进行存根。

  httpResponseBaseStub.SetupGet(x => x.OutputStream).Returns(new Mock<Stream>().Object);
  httpResponseBaseStub.SetupGet(x => x.ContentType).Returns("text/csv"); 

HttpResponseBase 中的所有属性和方法都是虚拟的,因此您可以使用 Moq.Mock 向您的 SUT 提供所有这些属性的虚假表示。有一些先进的模拟技术,例如AutoMocking,它可以帮助您删除一些不必要的模拟,但默认情况下将所有这些属性返回给您,但我不会详细介绍。

但是,这可能不是您所期望的,因为像我上面描述的 stubbinh/faking 值并没有真正为您需要在单元测试中验证的内容增加价值。它们只是虚假的价值。

那么下一个最好的方法是什么?

我认为最好通过验证一些使用预期值调用的关键 HttpResponseBase 属性来验证 ExportToCSV 的行为。例如,在您的单元测试中,您只需验证使用预期值调用的某些 HttpResponse 属性,如下所示。

    [TestMethod]
    public void CsvActionResultController_ExportToCSV_VerifyResponsePropertiesAreSetWithExpectedValues()
    {
        var sut = new HomeController();
        var httpResponseBaseMock = new Mock<HttpResponseBase>();

        //This would return a fake Output stream to you SUT 
        httpResponseBaseMock.Setup(x => x.OutputStream).Returns(new Mock<Stream>().Object);
        var httpContextBaseStub = new Mock<HttpContextBase>();
        httpContextBaseStub.SetupGet(x => x.Response).Returns(httpResponseBaseMock.Object);
        var controllerContextStub = new Mock<ControllerContext>();
        controllerContextStub.SetupGet(x => x.HttpContext).Returns(httpContextBaseStub.Object);
        sut.ControllerContext = controllerContextStub.Object;

        var result = sut.Index();

        httpResponseBaseMock.VerifySet(x => x.ContentType = "text/csv");
        httpResponseBaseMock.Verify(x => x.AddHeader("Content-Disposition", "attachment; filename=somefile.csv"));

        //Any other verifications...
    }

这里还有另一个示例,但使用类似验证的方法略有不同。根据我所描述的以及通过测试 ActionResult 类型是 FileContentResult,您可能会想出一个相当不错的单元测试。

Assert.IsInstanceOfType(actual, typeof(FileContentResult));

更新(包括 WriteFile 方法)

    protected void WriteFile(HttpResponseBase response)
    {
        // Add the header and the content type required for this view.
        string format = string.Format("attachment; filename={0}", "somefile.csv");
        response.AddHeader("Content-Disposition", format);
        response.ContentType = "text/csv"; //if you use base.ContentType, 
        //please make sure this return the "text/csv" during test execution.

        // Gets the current output stream.
        var outputStream = response.OutputStream;

        // Create a new memorystream.
        using (var memoryStream = new MemoryStream())
        {
            // WriteDataTable(memoryStream);
            outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }
    }
于 2013-11-02T12:57:53.683 回答