Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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<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 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?

like image 765
Daniel Avatar asked Jul 18 '11 06:07

Daniel


1 Answers

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);
like image 150
Darin Dimitrov Avatar answered Nov 14 '22 09:11

Darin Dimitrov