模拟HttpContext.Current.Server.MapPath使用起订量? [英] mock HttpContext.Current.Server.MapPath using Moq?

查看:666
本文介绍了模拟HttpContext.Current.Server.MapPath使用起订量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IM单元测试我的家控制器。这个测试工作得很好,直到我添加了一个新功能,将图像保存。



这是造成该问题的方法是这样的下面。

 公共静态无效SaveStarCarCAPImage(INT促进会)
{
字节[] = capBinary Motorpoint2011Data.RetrieveCapImageData(促进会);

如果(capBinary!= NULL)
{
的MemoryStream的iostream =新的MemoryStream();
的iostream =新的MemoryStream(capBinary);

//保存内存流作为图像
//读取数据,但不关闭,使用流之前。使用(流originalBinaryDataStream =的iostream)
{
VAR路径= HttpContext.Current.Server.MapPath(/ StarVehiclesImages)

;
路径= System.IO.Path.Combine(路径,促进会+.JPG);
图像的图像= Image.FromStream(originalBinaryDataStream);
图像缩放= image.GetThumbnailImage(500,375,空,新的IntPtr());
resize.Save(路径,System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}



由于通话是来自单元测试,HttpContext.Current为null,并抛出一个异常。阅读起订量以及一些关于使用起订量与会话教程后,我确定是可以做到的。



到目前为止,这个单元测试代码都拿出了,但问题是HTTPContext.Current总是空,而且还抛出异常。

 保护ControllerContext CreateStubControllerContext(控制器控制器)
{
变种httpContextStub =新的模拟< HttpContextBase>
{
默认值= DefaultValue.Mock
};

返回新ControllerContext(httpContextStub.Object,新的RouteData(),控制器);
}

[TestMethod的]
公共无效指数()
{
//安排
HomeController的控制器=新的HomeController();
controller.SetFakeControllerContext();

VAR背景= controller.HttpContext;

Mock.Get(上下文).Setup(S = GT; s.Server.MapPath(/ StarVehiclesImages))。返回(我的路);

//法案
的ViewResult结果= controller.Index()作为的ViewResult;

//断言
HomePageModel模型=(HomePageModel)result.Model;
Assert.AreEqual(欢迎来到ASP.NET MVC!,model.Message);
Assert.AreEqual(typeof运算(列表<车辆与GT),model.VehicleMakes.GetType());
Assert.IsTrue(model.VehicleMakes.Exists(X => x.Make.Trim()等于(福特,StringComparison.OrdinalIgnoreCase)));
}


解决方案

HttpContext.Current 的东西,如果你希望你的代码进行单元测试,你绝对应该永远不会使用。这是一个简单的返回null如果这是一个单元测试的情况下,不能被嘲笑没有Web上下文的静态方法。因此,重构你的代码一种方法是以下内容:

 公共静态无效SaveStarCarCAPImage(INT促进会,字符串路径)
{
字节[] = capBinary Motorpoint2011Data.RetrieveCapImageData(促进会,路径);

如果(capBinary!= NULL)
{
的MemoryStream的iostream =新的MemoryStream();
的iostream =新的MemoryStream(capBinary);

//保存内存流作为图像
//读取数据,但不关闭,使用流之前。使用(流originalBinaryDataStream =的iostream)
{
路径= System.IO.Path.Combine(路径,促进会+.JPG)

;
图像的图像= Image.FromStream(originalBinaryDataStream);
图像缩放= image.GetThumbnailImage(500,375,空,新的IntPtr());
resize.Save(路径,System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}

您看,现在这种方法不再依赖于任何网络上下文,并且可以被独立地测试。这将是调用者传递了正确的路径的责任。


im unit testing my home controller. This test worked fine until I added a new feature which saves images.

The method that’s causing the issue is this below.

    public static void SaveStarCarCAPImage(int capID)
    {
        byte[] capBinary = Motorpoint2011Data.RetrieveCapImageData(capID);

        if (capBinary != null)
        {
            MemoryStream ioStream = new MemoryStream();
            ioStream = new MemoryStream(capBinary);

            // save the memory stream as an image
            // Read in the data but do not close, before using the stream.

            using (Stream originalBinaryDataStream = ioStream)
            {
                var path = HttpContext.Current.Server.MapPath("/StarVehiclesImages");
                path = System.IO.Path.Combine(path, capID + ".jpg");
                Image image = Image.FromStream(originalBinaryDataStream);
                Image resize = image.GetThumbnailImage(500, 375, null, new IntPtr());
                resize.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }

As the call is coming from a unit test, HttpContext.Current is null and throws an exception. After reading about Moq and some of the tutorials about using Moq with sessions, im sure it can be done.

so far this the unit test code have come up with, but the issue is HTTPContext.Current is always null, and still throws the exception.

    protected ControllerContext CreateStubControllerContext(Controller controller)
    {
        var httpContextStub = new Mock<HttpContextBase>
        {
            DefaultValue = DefaultValue.Mock
        };

        return new ControllerContext(httpContextStub.Object, new RouteData(), controller);
    }

    [TestMethod]
    public void Index()
    {
        // Arrange
        HomeController controller = new HomeController();            
        controller.SetFakeControllerContext();

        var context = controller.HttpContext;

        Mock.Get(context).Setup(s => s.Server.MapPath("/StarVehiclesImages")).Returns("My Path");

        // Act
        ViewResult result = controller.Index() as ViewResult;

        // Assert
        HomePageModel model = (HomePageModel)result.Model;
        Assert.AreEqual("Welcome to ASP.NET MVC!", model.Message);
        Assert.AreEqual(typeof(List<Vehicle>), model.VehicleMakes.GetType());
        Assert.IsTrue(model.VehicleMakes.Exists(x => x.Make.Trim().Equals("Ford", StringComparison.OrdinalIgnoreCase)));
    }

解决方案

HttpContext.Current is something that you should absolutely never use if you ever expect your code to be unit tested. It is a static method which simply returns null if there is no web context which is the case of a unit test and cannot be mocked. So one way to refactor your code would be the following:

public static void SaveStarCarCAPImage(int capID, string path)
{
    byte[] capBinary = Motorpoint2011Data.RetrieveCapImageData(capID, path);

    if (capBinary != null)
    {
        MemoryStream ioStream = new MemoryStream();
        ioStream = new MemoryStream(capBinary);

        // save the memory stream as an image
        // Read in the data but do not close, before using the stream.

        using (Stream originalBinaryDataStream = ioStream)
        {
            path = System.IO.Path.Combine(path, capID + ".jpg");
            Image image = Image.FromStream(originalBinaryDataStream);
            Image resize = image.GetThumbnailImage(500, 375, null, new IntPtr());
            resize.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

You see, now this method no longer depends on any web context and can be tested in isolation. It will be the responsibility of the caller to pass the correct path.

这篇关于模拟HttpContext.Current.Server.MapPath使用起订量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆