Jus*_*tin 5 c# unit-testing moq mocking
这个问题与我发布的上一个问题有关.
如上所述,我能够将原始代码重构为两个单独的类; 我现在试图通过模拟部分(ExcelManager)来测试不依赖于Office.Interop对象的部分(ParseDataTable).
当我运行测试时,我的模拟对象只是部分工作,正在模拟GetColumnCount方法并在ParseDataTable对象中返回我的局部变量.
但是,未调用GetData模拟方法,而是将代码放入ExcelManager类的GetData方法中
用于创建模拟的代码:
MockExcel = new Mock<ExcelManager>("testfile.xls",0);
MockExcel.Setup(x => x.GetColumnCount()).Returns(columnCount);
MockExcel.Setup(x => x.GetData()).Returns(mockData);
MockExcel.Setup(x => x.Initialize());
Run Code Online (Sandbox Code Playgroud)
columnCount和mockData都是测试的局部变量,包含我基于测试的数据.
我正在测试的课程:
public class ParseDataTable
{
private const string TableSortOrder = "1 asc, 4 asc, 6 asc";
public DataTable GetRangeValue(ExcelManager excelManager)
{
var columnCount = excelManager.GetColumnCount();
var sheetData = excelManager.GetData();
var value = new DataTable();
for (var j = 1; j <= columnCount; j++)
{
value.Columns.Add(j.ToString());
}
for (var i = 1; i <= sheetData.GetLength(0); i++)
{
var row = value.NewRow();
var emptyCount = 0;
for (var j = 1; j <= columnCount; j++)
{
row[j - 1] = sheetData[i, j] ?? "";
if ((string)row[j-1] == "")
{
emptyCount++;
}
}
//if row is empty then no more data is expected
if (emptyCount == value.Columns.Count) break;
value.Rows.Add(row);
}
excelManager.Dispose();
return sortDataTable(value);
}
private DataTable sortDataTable(DataTable table)
{
table.DefaultView.Sort = TableSortOrder;
table = table.DefaultView.ToTable();
return table;
}
}
Run Code Online (Sandbox Code Playgroud)
ExcelManager类中需要模拟的方法:
public virtual int GetColumnCount()
{
var headerRng = _worksheet.get_Range(HeaderFirstCell, _miss);
headerRng = headerRng.get_End(XlDirection.xlToRight);
headerRng = _worksheet.get_Range(HeaderFirstCell, headerRng);
var headerData = (object[,])headerRng.Value2;
return headerData.GetLength(1);
}
public virtual object[,] GetData()
{
var last = _worksheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
var dataRng = _worksheet.get_Range(DataFirstCell, last);
return (object[,])dataRng.Value2;
}
Run Code Online (Sandbox Code Playgroud)
如果您从 ExcelManager 中提取一个接口作为接口(您可以将其称为 IExcelManager,但告诉大家我想出了一个绝妙的名字:-),那不是更容易吗?如果你通过了这一点,你的嘲笑困难应该不那么痛苦。