我想测试以下代码行:
... Bitmap uploadedPicture = Bitmap.FromStream(model.Picture.InputStream) as Bitmap; ...
图片是我的模型类型HttpPostedFileBase中的一个属性.
所以我想模拟一个HttpPostedFileBase属性进行单元测试:
model.Picture = new Mock<HttpPostedFileBase>().Object;
完全没问题.
现在我必须模拟InputStream,否则为null:
model.Picture.InputStream = new Mock<Stream>().Object;
这不工作,因为InputStream是只读(没有setter方法):
public virtual Stream InputStream { get; }
有没有一个好的和干净的方式来处理这个问题?
一个解决方案是在我的单元测试的派生类中覆盖HttpPostedFileBase.
任何其他想法?
解决方法
你好:)我做了类似的事情,
[TestInitialize] public void SetUp() { _stream = new FileStream(string.Format( ConfigurationManager.AppSettings["File"],AppDomain.CurrentDomain.BaseDirectory),FileMode.Open); // Other stuff }
而在测试本身,
[TestMethod] public void FileUploadTest() { // Other stuff #region Mock HttpPostedFileBase var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); var files = new Mock<HttpFileCollectionBase>(); var file = new Mock<HttpPostedFileBase>(); context.Setup(x => x.Request).Returns(request.Object); files.Setup(x => x.Count).Returns(1); // The required properties from my Controller side file.Setup(x => x.InputStream).Returns(_stream); file.Setup(x => x.ContentLength).Returns((int)_stream.Length); file.Setup(x => x.FileName).Returns(_stream.Name); files.Setup(x => x.Get(0).InputStream).Returns(file.Object.InputStream); request.Setup(x => x.Files).Returns(files.Object); request.Setup(x => x.Files[0]).Returns(file.Object); _controller.ControllerContext = new ControllerContext( context.Object,new RouteData(),_controller); // The rest... }
希望这可以为您的解决方案提供一个想法:)