【发布时间】:2016-06-09 18:45:00
【问题描述】:
我有以下代码:
public int LoadFilesAndSaveInDatabase(string filesPath)
{
var calls = new ConcurrentStack<GdsCallDto>();
var filesInDirectory = this._directoryProxy.GetFiles(filesPath);
if (filesInDirectory.Any())
{
Parallel.ForEach(filesInDirectory, file =>
{
var lines = this._fileProxy.ReadAllLines(file, Encoding.Unicode);
if (lines.Any())
{
// Reads the file and setup a new DTO.
var deserializedCall = this._fileManager.DeserializeFileContent(lines, Path.GetFileName(file));
// Insert the DTO in the database.
this._gdsCallsData.InsertOrUpdateGdsCall(deserializedCall);
// We keep track of the dto to count the number of restored items.
calls.Push(deserializedCall);
}
});
}
return calls.Count;
}
我有以下单元测试:
[TestMethod]
public void ShouldLoadFilesAndSaveInDatabase()
{
// Arrange
var path = RandomGenerator.GetRandomString(56);
var encoding = Encoding.Unicode;
var fileNameEnvironment = RandomGenerator.GetRandomString();
var fileNameModule = RandomGenerator.GetRandomString();
var fileNameRecordLocator = RandomGenerator.GetRandomString(6);
var fileNameTimestamp = RandomGenerator.GetRandomDateTime().ToString("O").Replace(':', 'o');
// We simulate the presence of 4 files.
var files = new List<string>
{
RandomGenerator.GetRandomString(255),
RandomGenerator.GetRandomString(255),
RandomGenerator.GetRandomString(255),
RandomGenerator.GetRandomString(255)
}.ToArray();
var expectedResult = 4;
this._directoryProxy.Expect(d => d.GetFiles(path))
.Return(files);
this._fileProxy.Expect(f => f.ReadAllLines(path, encoding))
.Return(files).Repeat.Times(files.Length);
// Act
var result = this._databaseReloadManager.LoadFilesAndSaveInDatabase(path);
// Assert
Assert.AreEqual(result, expectedResult);
this._directoryProxy.AssertWasCalled(d => d.GetFiles(path));
this._fileProxy.AssertWasCalled(f => f.ReadAllLines(path, Encoding.Unicode));
}
问题出在下面一行:
var lines = this._fileProxy.ReadAllLines(file, Encoding.Unicode);
即使我设置了期望值和返回值,当我运行单元测试时,它总是返回 null。
我正在使用 Rhino.Mocks,它在其他地方工作得非常好,但在那里却不行。
我在这里查看了一些讨论,但没有一个有帮助。可能是因为使用了 Parallel.ForEach 吗?有没有办法做这样的模拟?
如果您需要任何其他信息,请告诉我。
【问题讨论】:
-
你的名字很糟糕。什么是“_DirectoryProxy”,什么是“_FileProxy”?您是否希望应用程序能够读取不存在的文件?
-
@cFrozenDeath,这个的命名不是我的责任,它是我们公司框架的一部分。 “代理”类旨在避免直接调用 System.IO.File 和 System.IO.Directory 类,以便我们可以模拟它们,并且它们提供与 IO 类相同的功能。
标签: c# unit-testing rhino-mocks parallel.foreach