惩戒HttpPostedFileBase的InputStream和对单元测试 [英] Mocking HttpPostedFileBase and InputStream for unit-test
问题描述
我想测试code的以下行:
I want to test the following line of code:
...
Bitmap uploadedPicture = Bitmap.FromStream(model.Picture.InputStream) as Bitmap;
...
照片是在我的模型类型HttpPostedFileBase的属性。
所以,我想嘲笑一个HttpPostedFileBase属性单元测试:
Picture is a property in my model type HttpPostedFileBase. So I would like to mock a HttpPostedFileBase property for unit-testing:
model.Picture = new Mock<HttpPostedFileBase>().Object;
没有问题的。
现在我有嘲笑的InputStream,否则它为空:
Now I have to mock the InputStream, otherwise it's null:
model.Picture.InputStream = new Mock<Stream>().Object;
这是不工作的InputStream为只读(有没有setter方法):
This isn't working as the InputStream is read-only (hasn't a setter method):
public virtual Stream InputStream { get; }
有没有办法解决这个问题一个很好的和干净的方式?
一个解决办法是将覆盖HttpPostedFileBase中为我的单元测试派生类。
任何其他的想法?
Is there a good and clean way to handle this problem? One solution would be to override HttpPostedFileBase in a derived class for my unit-test. Any other idea?
推荐答案
您好:)我不喜欢的东西,
Hi there :) I did something like,
[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...
}
希望这可以提供一个想法,你的解决方案:)
Hope this can provide an idea to your solution :)
这篇关于惩戒HttpPostedFileBase的InputStream和对单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!