mock HttpContext.Current.Server.MapPath using Moq?
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.
I agree with the Darin´s answer but if you really need to moq the Server.MapPath function you could do something like this
//...
var serverMock = new Mock<HttpServerUtilityBase>(MockBehavior.Loose);
serverMock.Setup(i => i.MapPath(It.IsAny<String>()))
.Returns((String a) => a.Replace("~/", @"C:\testserverdir\").Replace("/",@"\"));
//...
Performing this, the mock will simply replace the ~/ with the c:\testserverdir\ function
Hope it helps!