我正在努力变得更擅长编写更清晰的代码,并为应用程序中的方法开发自动化测试,以便更快地测试应用程序并编写更灵活和可扩展的代码。虽然我认为我了解单元测试的基础知识,但是在开发针对特定方法的测试时遇到了麻烦。我最近参加了一门有关单元测试的在线课程,并且了解到,为了为接触外部资源的方法编写单元测试,您应该创建一个类,该类实现与该外部资源交互的代码,并提取该类的接口因此可以从提取的接口创建一个Mock实例。我认为使用Excel Interop库符合接触外部资源的资格,而我现在正在使用的方法旨在将Excel文件保存到用户的计算机。此方法的代码如下。
public void Save()
{
if (DoesFileExistInDirectory())
{
semesterGradeInformationWorkbook.Save();
}
else
{
semesterGradeInformationWorkbook.SaveAs(LocationAsURL);
}
}
private bool DoesFileExistInDirectory()
{
return File.Exists(LocationAsURL);
}
在这种情况下,如果文件已经存在,则可以在工作簿上调用保存功能。但是,如果文件不存在,则在工作簿上调用SaveAs操作以将文件保存到该位置。整个类的代码可以在这里查看。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace GradeCalculator
{
public class ExcelWorksheet
{
private Excel.Application excelApplication;
private Excel.Workbook semesterGradeInformationWorkbook;
private Excel.Worksheet classInformationWorksheet;
public string Name { get; private set; }
public string LocationAsURL { get; private set; }
public int UsedRows
{
get { return this.classInformationWorksheet.UsedRange.Rows.Count; }
}
public int UsedColumns
{
get { return this.classInformationWorksheet.UsedRange.Columns.Count; }
}
public ExcelWorksheet(string name)
{
InitializeExcel();
Name = name;
LocationAsURL = Path.Combine(Properties.Settings.Default.DefaultDirectory, Name + ".xlsx");
}
private void InitializeExcel()
{
excelApplication = new Excel.Application();
semesterGradeInformationWorkbook = excelApplication.Workbooks.Add();
classInformationWorksheet = semesterGradeInformationWorkbook.ActiveSheet;
excelApplication.Visible = true;
}
public void Save()
{
if (DoesFileExistInDirectory())
{
semesterGradeInformationWorkbook.Save();
}
else
{
semesterGradeInformationWorkbook.SaveAs(LocationAsURL);
}
}
private bool DoesFileExistInDirectory()
{
return File.Exists(LocationAsURL);
}
}
}
关于如何重构代码的任何技巧,以便使代码更具扩展性,我可以为其编写单元测试?任何其他有关如何改进类和方法以更好地实现更好的面向对象设计的技巧也将不胜感激。