asp.net mvc 3 -如何在c#中进行单元测试

本文关键字:单元测试 mvc net asp | 更新日期: 2023-09-27 17:54:02

我正在学习单元测试如何使用nunit和rhino mock对该方法进行单元测试?

public ActionResult PrintCSV(Byte[] bytes, string fileName)
{
    var file = File(bytes, "application/vnd.ms-excel");
    var cd = new System.Net.Mime.ContentDisposition()
    {
        CreationDate = DateTime.Now,
        FileName = fileName,
        Inline = false
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return file;
}

asp.net mvc 3 -如何在c#中进行单元测试

您需要模拟HttpContext。这里有一个例子(它是MSTest,但我猜移植到NUnit不会很痛苦——你只需要重命名几个属性):

[TestMethod]
public void PrintCSV_Should_Stream_The_Bytes_Argument_For_Download()
{
    // arrange 
    var sut = new HomeController();
    var bytes = new byte[] { 1, 2, 3 };
    var fileName = "foobar";
    var httpContext = MockRepository.GenerateMock<HttpContextBase>();
    var response = MockRepository.GenerateMock<HttpResponseBase>();
    httpContext.Expect(x => x.Response).Return(response);
    var requestContext = new RequestContext(httpContext, new RouteData());
    sut.ControllerContext = new ControllerContext(requestContext, sut);
    // act
    var actual = sut.PrintCSV(bytes, fileName);
    // assert
    Assert.IsInstanceOfType(actual, typeof(FileContentResult));
    var file = (FileContentResult)actual;
    Assert.AreEqual(bytes, file.FileContents);
    Assert.AreEqual("application/vnd.ms-excel", file.ContentType);
    response.AssertWasCalled(
        x => x.AppendHeader(
            Arg<string>.Is.Equal("Content-Disposition"),
            Arg<string>.Matches(cd => cd.Contains("attachment;") && cd.Contains("filename=" + fileName))
        )
    );
}

正如您所看到的,这里有一些管道代码来设置测试。我个人使用MvcContrib。TestHelper,因为它简化了许多管道代码,并使测试更具可读性。看看这个:

[TestClass]
public class HomeControllerTests : TestControllerBuilder
{
    private HomeController sut;
    [TestInitialize]
    public void TestInitialize()
    {
        this.sut = new HomeController();
        this.InitializeController(this.sut);
    }
    [TestMethod]
    public void PrintCSV_Should_Stream_The_Bytes_Argument_For_Download()
    {
        // arrange 
        var bytes = new byte[] { 1, 2, 3 };
        var fileName = "foobar";
        // act
        var actual = sut.PrintCSV(bytes, fileName);
        // assert
        var file = actual.AssertResultIs<FileContentResult>();
        Assert.AreEqual(bytes, file.FileContents);
        Assert.AreEqual("application/vnd.ms-excel", file.ContentType);
        this.HttpContext.Response.AssertWasCalled(
            x => x.AppendHeader(
                Arg<string>.Is.Equal("Content-Disposition"),
                Arg<string>.Matches(cd => cd.Contains("attachment;") && cd.Contains("filename=" + fileName))
            )
        );
    }
}

现在测试更加清晰了,因为我们可以立即看到初始化阶段、被测方法的实际调用和断言。

备注:所有这些都说,我不太明白一个控制器动作的点,把字节数组作为参数只是流回客户端。我的意思是,为了调用它,客户端需要已经拥有文件,那么有什么意义呢?但我想这只是为了说明。在你的实际方法中,字节数组不是作为参数传递的,而是在你的控制器动作中从一些外部依赖项中检索的。在这种情况下,您也可以模拟这种依赖关系(当然,假设您已经正确地构建了您的层,并且它们是足够弱耦合的)。