我有一个我正在测试的方法。此方法的构造函数调用其基类构造函数,然后在其基类构造函数中设置一些成员,然后执行一个方法从数据库中获取数据,然后将一些数据库值设置为更多成员(所有这些都在构造函数中完成)。
为了测试我的原始方法,我是否应该在构造函数中删除对数据库的调用并对其进行重构,以便它只设置一些成员,然后我可以轻松地在我的测试中运行构造函数并存根所有正在传递的接口(在这种情况下为 1)或者我应该尝试在构造函数中填充进行数据库调用的方法?
// method under test
public override DateTime ResolveDate(ISeries comparisonSeries, DateTime targetDate)
{
switch (comparisonSeries.Key)
{
case SeriesKey.SomeKey1:
case SeriesKey.SomeKey2:
case SeriesKey.SomeKey3:
case SeriesKey.SomeKey4:
case SeriesKey.SomeKey5:
return DateHelper.PreviousOrCurrentQuarterEnd(targetDate);
default:
break;
}
return base.ResolveDate(comparisonSeries, targetDate);
}
// constructor
public ReportForm(SeriesKey key, IAppCache cache)
: base(key, cache)
{
//sets some base members here.
}
// base class that the constructor calls
public abstract class SeriesBase : ISeries
{
#region variables
protected IAppCache clientCache;
// other members below
// base constructor
public SeriesBase(SeriesKey key, IAppCache cache)
{
this.key = key;
this.clientCache = cache;
this.infoPack = new SeriesInfo();
this.InitalizeSeries();
}
private void InitalizeSeries()
{
Dictionary<string, object> qInfoSQL = new Dictionary<string, object>();
qInfoSQL.Add("@SeriesID", this.key.ToIntString());
DBServiceResult result = this.clientCache.DBService.FetchFromDB("spSeriesInit", CommandType.StoredProcedure, qInfoSQL);
if (result.Failed)
throw new NotImplementedException("whoat");
this.SetPublishTimeLag(result.XMLResult.Elements("tbl0").FirstOrDefault());
this.AddFormView(result.XMLResult.Elements("tbl1").FirstOrDefault());
this.AddPresentation(result.XMLResult.Elements("tbl2").DefaultIfEmpty(null).FirstOrDefault());
this.SetBridge();
this.InitializeGenerics();
}
this.clientCache.DBService.FetchFromDB(...) 方法正在调用另一个调用方法 FetchFromDB 的接口 DBService,此 fetchfromDb 方法转到 QSL 服务器并检索数据集。
这是我的测试方法。
public void TestResolveDate()
{
//using (ShimsContext.Create())
//{
// Stat.Pi.Data.Fakes.ShimAuthenticator
//}
var appCache = new Fakes.StubIAppCache();
appCache.DBServiceGet = DbServiceGet;
ReportFORM formReport = new ReportForm(SeriesKey.SomeKey1, appCache);
var series = new Fr Fakes.StubISeries();
DateTime date = formReport.ResolveDate(series, DateTime.Now);
//Assert.
}
private IDBService DbServiceGet()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("@SeriesID", "50");
var service = new Fakes.StubIDBService();
service.FetchFromUnicornStringCommandTypeDictionaryOfStringObject = (s, type, arg3) => dict
return service;
}