我正在尝试对遗留项目进行测试。代码的编写方式通常是可测试的,但是一些第三方依赖项不是。我正试图围绕如何对看起来像这样的东西进行单元测试:
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);
}
}
}
我知道很多人会建议使用 Mocks 或 Stubs 来传递而不是接口,但是对于这实际上是如何有益的,我有点困惑。似乎这只会确保调用适当的方法,这让我觉得有些空洞,而且与作业的实施相结合,无法成为真正有效的测试。最终问题变成了,您如何对不返回任何值并且实际上只会导致副作用的东西进行单元测试,而不只是测试它是否按照您所说的方式实现?