我有一个摘要对象,他们的职责实际上是将很多东西组合在一起并创建一个摘要报告,后来将序列化为XML。 在这个对象中,我有很多这样的结构:
public class SummaryVisit : Visit, IMappable
{
public int SummaryId { get; set; }
public int PatientId { get; set; }
public int LocationId { get; set; }
public IMappable Patient
{
get
{
return new SummaryPatient(PatientBusinessService.FindPatient(this.PatientId));
}
}
public IMappable Location
{
get
{
return new SummaryLocation(LocationBusinessService.FindLocation(this.LocationId));
}
}
public IEnumerable<IMappable> Comments
{
get
{
return new SummaryComments(CommentBusinessService.FindComments(this.SummaryId, Location));
}
}
// ... can be a lot of these structures
// ... using different business services and summary objects
public IEnumerable<IMappable> Tasks
{
get
{
return new SummaryTasks(TaskBusinessService.FindTasks(this));
}
}
}
PatientBusinessService,LocationBusinessService等是静态的。 并且这些SummaryPatient,SummaryLocation等中的每一个都具有相同类型的结构。
重构和单元测试的最佳方法是什么?
尝试通过接口代理(或重构静态到非静态类和接口)将调用替换为静态调用,但是这个类只是将很多这些接口作为构造函数注入东西而开始变得超级贪婪。另外,这些接口内部有一个使用的方法(如果我只是为了这个摘要需要创建它)。
一旦这是一个摘要对象,通常这个静态服务只使用一次整个结构来获得适当的输出属性。
答案 0 :(得分:0)
您可以将测试更改为更加集成(当时测试多个类)。您可以尝试将服务修改为更通用,并能够从不同的来源(如TestDataProvider和您当前的数据提供者)获取数据。
我认为更好的解决方案是修改您要测试的类:
对属性使用强类型并获得所有好处。我认为您应该返回更多特定类型而不是 IMappable
看起来你的一些数据存储在类(ids)中,而某些数据则不存在(IMappable对象引用)。我会重构这个来保存对class中对象的引用:
private SummaryPatient _patient;
public SummaryPatient Patient
{
get
{
if (_patient == null)
_patient = new SummaryPatient(PatientBusinessService.FindPatient(this.PatientId));
return _patient;
}
}
然后,您可以在构造函数中分配测试数据,或者仅为单元测试创建静态方法CreateDummy(...)
。然后,此方法应使用CreateDummy
作为子对象。您可以在单元测试中使用它。