HttpFileCollectionBase:模拟计数属性

时间:2011-07-18 06:49:16

标签: asp.net-mvc tdd moq

我尝试模拟HttpFileCollectionBase实例的Count-Property - 但不知何故它不起作用。

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

如您所见,我创建了一个模拟的HttpRequest,我将其注入到被测系统中。 Count-Property被定义为返回1 - 但它总是返回0.我正在使用Moq。

我做错了什么?

2 个答案:

答案 0 :(得分:13)

Scott Hanselman blogged about this。问题是以下几行:

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

尝试这样,它应该有效:

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

答案 1 :(得分:0)

以下是使用NSubstitute的更深层示例,它允许您预览文件集

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

示例来电者使用情况https://stackoverflow.com/a/1760523/37055