Mocking OpenXML with Moq

这一生的挚爱 提交于 2019-12-07 09:53:37

Since ExcelDocument is the system under test then there is no need to mock IExcelDocument. You should mock/stub/fake the dependencies needed to test the SUT

Now I was able to get your test to pass like this...

public class Test {
    [TestClass()]
    public class ExcelUpdateLogicTests {
        [TestMethod()]
        public void Given_SheetName_ExcelDocument_Should_GetWorkseetPart() {
            //Arrange
            var stream = new MemoryStream();//Avoid having to use actual file on disk
            var spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());

            // Add a sheets list.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

            // Append the new worksheet and associate it with the workbook.
            string expectedId = workbookpart.GetIdOfPart(worksheetPart);
            string sheetName = "mySheet";

            Sheet sheet = new Sheet() {
                Id = expectedId,
                SheetId = 1,
                Name = sheetName
            };
            sheets.Append(sheet);

            var wrapper = new SpreadsheetDocumentWrapper(spreadsheetDocument);

            string fakeFilePath = "path";
            var sut = new ExcelDocument(fakeFilePath);

            //Act
            WorksheetPart result = sut.GetWorksheetPart(wrapper, sheetName);

            //Assert
            Assert.IsNotNull(result);
            var actualId = workbookpart.GetIdOfPart(result);
            Assert.AreEqual(expectedId, actualId);
        }
    }
}

The process of doing so however raised some questions about the current design.

If the whole point of creating the abstraction was to hide the implementation details and reduce the tight coupling on the external framework to make things easier to mock and test then having to create an actual SpreadsheetDocument and wrapping it for the test seems redundant.

A lot of the parts of the framework are difficult to mock given their internal generation. I would hide those behind other abstractions, but given that I do not know enough about the end goal of this system I cannot advise as to what design structure you should be taking.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!