This question is related to the previous question that I posted.
As already mentioned, I managed to reorganize the source code into two separate classes; Now I'm trying to check the part (ParseDataTable), which is independent of Office.Interop objects, mocking the part (ExcelManager).
When I run the tests, my mocked object only partially works, the GetColumnCount method mocks correctly and returns my local variable in the ParseDataTable object.
However, the GetData bullying method is not called; instead, the code goes into the GetData method in the ExcelManager class
Code used to create the layout:
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());
columnCount and mockData are local variables for the test with the data on which I base my tests.
The class I'm testing is:
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 (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;
}
}
Ways to mock the ExcelManager class:
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;
}