我有以下代碼:模擬方法始終返回null
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嗎?有沒有辦法做這樣的模擬?
如果您需要任何其他信息,請讓我知道。
你有可怕的壞namings那裏。什麼是「_DirectoryProxy」和什麼是「_FileProxy」?您是否期望應用程序能夠讀取不存在的文件? –
@cFrozenDeath,這個命名不是我的責任,它是我們公司框架的一部分。 「代理」類旨在避免直接調用System.IO.File和System.IO.Directory類,以便我們可以模擬它們,並且它們提供了與IO類相同的功能。 – DotNetMatt