我是新手,我以前从未做过单元测试.
我制作了一个控制台应用程序来压缩文件并发送电子邮件.现在我想进行单元测试.但我不确定我的代码是否可测试.
例如,我有一个叫做的方法 -
public static void readAndEmailCsvFiles(string filePath)
{
DirectoryInfo directory = new DirectoryInfo(filePath);
var files = directory.GetFiles("*.csv", SearchOption.AllDirectories);
var dirDate = string.Format("{0:yyyy-MM-dd HH-mm}", DateTime.Now);
bool isExists = System.IO.Directory.Exists(filePath + "\\" + "PROCESSED" + "\\" + dirDate);
if (!isExists)
{
System.IO.Directory.CreateDirectory(filePath + "\\" + "PROCESSED" + "\\" + dirDate);
}
try
{
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
foreach (var file in files)
{
Console.WriteLine("Processing File : " + file + "\n");
zip.AddFile(file.FullName, "");
zip.Save(Path.Combine(filePath, "PROCESSED", dirDate, file.Name) + ".zip");
sendEmail.SendMailMessage(Path.Combine(filePath, "PROCESSED", dirDate, file.Name) + ".zip");
}
}
foreach (var file in files)
{
File.Delete(file.FullName);
Console.WriteLine("");
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
我如何为上述方法创建测试?
你的班级负责太多责任
例如:获取文件列表的
逻辑拉链文件的
逻辑发送电子邮件的逻辑
基本上这形成了你的工作流程
我向您提出的第一个建议是将这些职责分散到不同的服务(类)
中将
这些服务注入您的工作流程
自行
测试服务测试使用所有这些服务的工作流程以完成工作
例如:给出文件的EmailService类发送电子邮件
例如:具有FileRepository类,该类提取给定路径的文件列表
等
注入这些服务的一种可能方式如下所示
public class ClassName
{
public ClassName(IEmailService emailService, IFileRespository fileRepository)
{
// You might want store the reference to these injected services
// and later use them to perform useful work
}
public void DoSomething()
{
// Do Something useful
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |