我正在尝试将一个遗留项目置于测试中。代码的编写方式通常是可测试的,但某些第三方依赖关系不是。我试图总结我的周围,看起来如何进行单元测试是这样的头:单元测试作业组件C#
class InsightEmailJob : NHibernateJob
{
public IInsightEmailService InsightEmailService { get; set; }
public IReportService ReportService { get; set; }
public ITemplatedNotifier TemplatedNotifier { get; set; }
public string ReplyEmail { get; set; }
public string ReplyName { get; set; }
public InsightEmailJob(ISession session,
ILog log,
IInsightEmailService insightEmailService,
IReportService reportService,
ITemplatedNotifier templatedNotifier,
SystemReplyEmailSpec systemReplyEmailSpec)
: base(session, log)
{
InsightEmailService = insightEmailService;
ReportService = reportService;
TemplatedNotifier = templatedNotifier;
ReplyEmail = systemReplyEmailSpec.ReplyEmail;
ReplyName = systemReplyEmailSpec.ReplyName;
}
public int AccountID{ get; set; }
private Account mAccount;
public Account Account
{
get
{
if (this.mAccount == null)
{
mAccount = this.InsightEmailService.Get<Account>(AccountID);
}
return mAccount;
}
}
protected override void DoWork(JobExecutionContext context)
{
var insightEmail = InsightEmailService.FindAndIncrementEmailForAccount(Account);
var report = ReportService.LoadMultiReportByName(insightEmail.ReportName);
var reportData = ReportService.Execute(report, new ParameterValuesDictionary(Account, DateTime.Now.AddDays(-7), DateTime.Now, 0));
var templateData = new Hashtable {{"data", reportData}, {"account", Account}};
foreach (var u in Account.Users.Where(x => x.Notify))
{
TemplatedNotifier.Send(u.UserName, ReplyName, ReplyEmail, insightEmail.TemplateName, templateData);
}
}
}
据我了解,很多人会建议使用嘲笑或存根在传递,而不是接口,但是我有点困惑,这实际上是有益的。看起来,这样做只会确保调用适当的方法,这让我觉得有些空洞,并且与作业的实现相关联成为一个非常有效的测试。最终问题就变成了,你如何单元测试不返回值的东西,而只是在没有按照你说的方式进行测试的情况下进行测试才会产生副作用?
嘲笑的方法一个例子,我不知道怎样添加另一个抽象这里是要减少复杂性。发送*的电子邮件已被抽象为已实现接口的类,我*已*使用接口。 IInsightEmailService是加载InsightEmails的存储库。我可以将SystemReplyEmailSpec推入通知程序,并且这会将相关性降低到5,但我没有看到胜利。为什么要把另一个类放到这个地方(即相同的东西)比使用已经存在的代码更好? – 2013-05-01 21:21:53