HttpFileCollectionBase: Mocking Count-Property

I am trying to make fun of the Count-Property of an HttpFileCollectionBase instance, but somehow this does not 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); 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 can see, I create a ridiculous HttpRequest that I insert into the system under test. The Count-Property is defined to return 1 - but it always returns 0. I use Moq.

What am I doing wrong?

+4
source share
2 answers

Scott Hanselman talked about this . The problem is the following line:

 fakedRequest.SetupGet(x => x.Files[0]).Returns(fakedFile.Object); 

Try 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); 
+10
source

Here's a deeper example using NSubstitute that lets you choose from a collection of files

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

Caller Usage Example fooobar.com/questions/103604 / ...

0
source

All Articles