在C#中,使用EPPlus库进行单元测试时,通常会使用xUnit、NUnit或MSTest等测试框架。以下是一个使用xUnit进行单元测试的示例:
Install-Package EPPlus
Install-Package xunit
Install-Package xunit.runner.visualstudio
创建一个Excel文件,例如SampleData.xlsx
,并在其中添加一些数据。
创建一个名为ExcelHelper.cs
的类,用于处理Excel文件的读取和写入操作:
using OfficeOpenXml;
using System.IO;
using System.Linq;
public class ExcelHelper
{
public static void WriteToExcel(string filePath, params object[,] data)
{
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
worksheet.Cells[i + 1, j + 1].Value = data[i, j];
}
}
package.SaveAs(new FileInfo(filePath));
}
}
public static object[,] ReadFromExcel(string filePath)
{
using (var package = new ExcelPackage(new FileInfo(filePath)))
{
var worksheet = package.Workbook.Worksheets["Sheet1"];
var data = worksheet.Cells.Select(c => c.Value).ToArray();
var result = new object[data.Length / 2, 2];
for (int i = 0; i < result.GetLength(0); i++)
{
result[i, 0] = data[i * 2];
result[i, 1] = data[i * 2 + 1];
}
return result;
}
}
}
ExcelHelperTests.cs
的测试类,使用xUnit框架对ExcelHelper
类进行单元测试:using System.IO;
using Xunit;
public class ExcelHelperTests
{
[Fact]
public void WriteToExcel_ShouldWriteDataToExcelFile()
{
// Arrange
var filePath = "SampleData.xlsx";
var data = new object[,]
{
{ "Name", "Age" },
{ "John", 30 },
{ "Jane", 28 }
};
// Act
ExcelHelper.WriteToExcel(filePath, data);
// Assert
Assert.True(File.Exists(filePath));
}
[Fact]
public void ReadFromExcel_ShouldReadDataFromExcelFile()
{
// Arrange
var filePath = "SampleData.xlsx";
var data = new object[,]
{
{ "Name", "Age" },
{ "John", 30 },
{ "Jane", 28 }
};
ExcelHelper.WriteToExcel(filePath, data);
// Act
var result = ExcelHelper.ReadFromExcel(filePath);
// Assert
Assert.Equal("Name", result[0, 0]);
Assert.Equal("Age", result[0, 1]);
Assert.Equal("John", result[1, 0]);
Assert.Equal(30, result[1, 1]);
Assert.Equal("Jane", result[2, 0]);
Assert.Equal(28, result[2, 1]);
}
}
这个示例展示了如何使用xUnit框架对ExcelHelper
类进行单元测试。你可以根据需要修改和扩展这个示例,以适应你的项目需求。