简体   繁体   中英

How can I Unit Test using mock with EPPlus?

I'm using EPPLus for a project, and I'm trying to just create an Excel Worksheet in memory to mock it.

the class I'm using for unit testing has a method

public ExcelPackage GetExcelPackage()
{
    using (var package = new ExcelPackage())
    {
        ExcelWorksheet returnWorksheet = package.Workbook.Worksheets.Add("worksheet");
        returnWorksheet.Cells[1, 1].Value = "043";
        returnWorksheet.Cells[1, 2].Value = "21677";
        returnWorksheet.Cells[1, 3].Value = "100";
        returnWorksheet.Cells[1, 4].Value = String.Empty;
        returnWorksheet.Cells[1, 5].Value = "12292016";
        returnWorksheet.Cells[1, 6].Value = String.Empty;
        return package;
    }
}

In my InputFileController, I get a null object error when I call package.Workbook.Worksheets.First.

public static IInputFileRepository ReadExcelFile(IFileDataSource excelFileDataSource)
    {
        FileInfo fileToRead = new FileInfo(excelFileDataSource.InputFile);
        List<string> lines = new List<string>();
        ExcelPackage package = excelFileDataSource.GetExcelPackage();
        ExcelWorksheet worksheet = package.Workbook.Worksheets.First();

Any idea what I could be doing wrong?

So, it looks like I had an unrelated bug. Rather than having my IFileDataSource return an ExcelPackage, I have it return the filename, and use EPPlus to open and read that file from my InputController.

 public static IInputFileRepository ReadExcelFile(IFileDataSource excelFileDataSource)
    {
        FileInfo fileToRead = new FileInfo(excelFileDataSource.InputFile);
        List<string> lines = new List<string>();
        var fileInfo = new FileInfo(excelFileDataSource.InputFile);
        using (var package = new ExcelPackage(newFile: fileInfo))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
            for (int rowIndex = 2; rowIndex <= worksheet.Dimension.End.Row; rowIndex++)

Null reference error happens due to disposing of the object - which is due to the using statement around the code block.

I'm putting my answer here in case anybody comes and wonders about the root cause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM