我在這個週末一直在抨擊我的頭。基本上我正在做一個生命遊戲的代碼卡塔,它涉及閱讀一個文本文件。我採用包含網格的二維表示的文本文件,並將所有點存儲在List列表中。我試圖嘲笑從文件獲得的文本輸入只是'\ n'一個新行,所以我可以編寫單元測試,檢查List列表中是否創建了一個新列表。我創建了一個文件包裝來處理文本文件的閱讀,這就是我想要嘲笑的。該代碼符合要求,但測試失敗並顯示錯誤消息「System.ArgumentException:指定的路徑不是合法表單」。它似乎仍然期待着一個文件路徑,但嘲笑應該改變這種行爲嗎?任何幫助,將不勝感激。如何在Monodevelop上使用Moq框架在C#中讀取文件時輸出文本輸出
using System.Collections.Generic;
namespace GameOfLife
{
public class InitializeGrid
{
public InitializeGrid()
{
}
public List<List<char>> CreateCharMatrix (string filePathName)
{
// Reads in the text file containing the grid data
FileWrapper fileWrapper = new FileWrapper();
string inputGridTextFile = fileWrapper.ReadTextFromFile (filePathName);
// Creates character matrix and initialises the first sub List
List<List<char>> charMatrix = new List<List<char>>();
charMatrix.Add(new List<char>());
int rowIndex = 0;
int colIndex = 0;
foreach (char cell in inputGridTextFile) {
if (cell == '\n') {
charMatrix.Add (new List<char>());
rowIndex++;
colIndex = 0;
} else {
charMatrix [rowIndex] [colIndex] = cell;
colIndex++;
}
}
return charMatrix;
}
}
}
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Moq;
namespace GameOfLife
[TestFixture()]
public class InitializeGridTest
{
[Test()]
public void CreateCharMatrix_EnsuresThatWhenEndOfLineReachedNewSubListCreated()
{
//Arrange
InitializeGrid initializeGrid = new InitializeGrid();
List<List<char>> charMatrix;
string filePathName = " ";
Mock<IFileWrapper> mockFileWrapper = new Mock<IFileWrapper>();
mockFileWrapper.Setup<string> (m => m.ReadTextFromFile (It.IsAny<string>())).Returns ("\n");
mockFileWrapper.Setup (m => m.ReadTextFromFile (It.IsAny<string>())).Returns ("\n");
//Act
charMatrix = initializeGrid.CreateCharMatrix (filePathName);
int countProvingAnAdditionalListHasBeenAdded = charMatrix.Count;
//Assert
Assert.AreEqual (2, countProvingAnAdditionalListHasBeenAdded);
}
}
using System;
using System.IO;
namespace GameOfLife
{
public class FileWrapper : IFileWrapper
{
public string ReadTextFromFile(string path)
{
return File.ReadAllText (path);
}
}
}
using System;
namespace GameOfLife
{
public interface IFileWrapper
{
string ReadTextFromFile(string filePathName);
}
}
非常感謝!只需輸入此代碼,我的測試已通過哈哈。 –