HttpFileCollectionBase: Mocking Count-Property
I try to mock the Count-Property of an instance of HttpFileCollectionBase - but somehow it doesn't work.
var fakedRequest = new Mock<H开发者_开发问答ttpRequestBase>();
var fakedFile = new Mock<HttpPostedFileBase>();
fakedFile.SetupGet(x => x.InputStream).Returns(inputStream);
var fakedFileCollection = new Mock<HttpFileCollectionBase>();
fakedFileCollection.SetupGet(x => x.Count).Returns(1);
fakedRequest.SetupGet(x => x.Files).Returns(fakedFileCollection.Object);
fakedRequest.SetupGet(x => x.Files[0]).Returns(fakedFile.Object);
var sut = new TestableExploreController(null, fakedTemporaryStorageRepository.Object)
{
HttpRequest = fakedRequest.Object
};
As you see, I create a mocked HttpRequest, which I inject to the system under test. The Count-Property is defined to return 1 - but it always returns 0. I'm using Moq.
What am I doing wrong?
Scott Hanselman blogged about this. The problem is the following line:
fakedRequest.SetupGet(x => x.Files[0]).Returns(fakedFile.Object);
Try like this and it should work:
var fakedRequest = new Mock<HttpRequestBase>();
var fakedFile = new Mock<HttpPostedFileBase>();
fakedFile.SetupGet(x => x.InputStream).Returns(inputStream);
var fakedFileCollection = new Mock<HttpFileCollectionBase>();
fakedFileCollection.SetupGet(x => x.Count).Returns(1);
fakedFileCollection.SetupGet(x => x[0]).Returns(fakedFile.Object);
fakedRequest.SetupGet(x => x.Files).Returns(fakedFileCollection.Object);
Here's a deeper example using NSubstitute
that allows you to foreach over the file collection
var request = Substitute.For<HttpRequestBase>();
var firstFile = Substitute.For<HttpPostedFileBase>();
firstFile.ContentLength.Returns(1);
firstFile.FileName.Returns("firstFile.txt");
firstFile.ContentType.Returns("text");
firstFile.InputStream.Returns(new MemoryStream());
var secondFile = Substitute.For<HttpPostedFileBase>();
secondFile.ContentLength.Returns(1);
secondFile.FileName.Returns("secondFile.txt");
secondFile.ContentType.Returns("text");
secondFile.InputStream.Returns(new MemoryStream());
var fileKeys = new[] { "1", "2" };
var files = Substitute.For<HttpFileCollectionBase>();
files.GetEnumerator().Returns(fileKeys.GetEnumerator());
files[fileKeys[0]].Returns(firstFile);
files[fileKeys[1]].Returns(secondFile);
request.Files.Returns(files);
Example caller usage https://stackoverflow.com/a/1760523/37055
精彩评论