gpt4 book ai didi

c# - 使用最小起订量模拟 HttpContext.Current.Server.MapPath?

转载 作者:可可西里 更新时间:2023-11-01 08:36:12 26 4
gpt4 key购买 nike

我正在对我的家庭 Controller 进行单元测试。在我添加保存图像的新功能之前,此测试运行良好。

导致问题的方法如下所示。

    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);
}
}
}

由于调用来自单元测试,因此 HttpContext.Current 为 null 并引发异常。在阅读了 Moq 和一些关于在 session 中使用 Moq 的教程后,我确信它可以完成。

到目前为止,单元测试代码已经出来了,但问题是 HTTPContext.Current 始终为 null,并且仍然抛出异常。

    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 如果您希望对代码进行单元测试,则绝对不要使用它。它是一个静态方法,如果没有 Web 上下文(这是单元测试的情况并且不能被模拟),它只会返回 null。因此,重构代码的一种方法如下:

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);
}
}
}

你看,现在这个方法不再依赖于任何网络上下文,可以单独测试了。调用者有责任传递正确的路径。

关于c# - 使用最小起订量模拟 HttpContext.Current.Server.MapPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com