我有一个在单独的类MethodA
中调用MethodB
的(一个遵循接口的)。
MethodB
里面有一个StreamReader
,所以我将调用重构new StreamReader()
为一个新的MethodC
(在同一个类中MethodB
)。
为了测试MethodA
,我需要模拟MethodB
,但我还需要能够通过MethodB
模拟进行测试MethodC
。
(我想很明显我有点迷路了。)
namespace JimBob.CsvImporter.Entity
{
public interface IIOManager
{
TextReader ReturnReader(string path);
int GetNumberOfColumnsInFile(string filePath, List<string> errorMessageList);
}
public class IOManager : IIOManager
{
//MethodC
public TextReader ReturnReader(string filePath)
{
return new StreamReader(filePath);
}
//MethodB
public int GetNumberOfColumnsInFile(string filePath, List<String> errorMessageList)
{
int numberOfColumns = 0;
string lineElements = null;
try
{
using (StreamReader columnReader = (StreamReader)ReturnReader(filePath))
{
lineElements = columnReader.ReadLine();
string[] columns = lineElements.Split(',');
numberOfColumns = columns.Length;
}
return numberOfColumns;
}
catch (Exception ex)
{
errorMessageList.Add(ex.Message);
return -1;
}
}
}
public class EntityVerification
{
private IIOManager _iomgr;
public EntityVerification(IIOManager ioManager)
{
this._iomgr = ioManager;
}
//MethodA
public void ValidateNumberOfColumns(
string filePath, int userSpecifiedColumnCount,
List<String> errorMessageList
)
{
int numberOfColumnsInFile =
_iomgr.GetNumberOfColumnsInFile(filePath, errorMessageList);
if (userSpecifiedColumnCount != numberOfColumnsInFile) errorMessageList.Add(
"Number of columns specified does not match number present in file.");
}
目前我的测试如下:
[Test]
public void GetNumberOfColumnsInFile_ReturnsNumberOfColumns_Returns6()
{
Mock<IIOManager> mock = new Mock<IIOManager>();
mock.Setup(x => x.ReturnReader(It.IsAny<string>())).Returns(
new StringReader("the,big,fat,dog,ate,cats"));
EntityVerification testObject = new EntityVerification(mock.Object);
List<String> errorMessageList = new List<string>();
int i = testObject.GetNumberOfColumnsInFile("blabla.txt", errorMessageList);
Assert.AreEqual(i , 6);
}
但这是在它是实体验证类的一部分时使用的。
我错过了什么吗?任何援助将不胜感激!