单元测试耦合方法
本文关键字:方法 耦合 单元测试 | 更新日期: 2023-09-27 18:32:59
在下面的示例中,如果我无法设置 aggregationInfo 对象,如何为 Deaggregate() 方法编写单元测试?
public class Aggregator
{
private AggregationInfo aggregationInfo;
public List Aggregate(List objects)
{
//set aggregationInfo
}
public List Deaggregate(List aggregatedObjects)
{
//use aggregationInfo for the deagregation
}
}
我会通过调用Aggregate
然后调用Deaggregate
来测试这一点,通过使用不同的列表调用聚合并验证在这些情况下解聚中的预期行为来提供不同的场景
如果要确保仅对方法进行单元测试,可以执行以下操作:
public class Aggregator
{
private AggregationInfo aggregationInfo;
private readonly IAggregator aggregator;
private readonly IDeaggragator deaggragotor;
public Aggregator(IAggregator aggregator, IDeaggragator deaggragotor)
{
this.aggregator = aggregator;
this.deaggragotor = deaggragotor;
}
public List Aggregate(List objects)
{
this.aggregationInfo = aggregator.Aggregate(objects);
return someListIDontKnowWhereYouGetThisFrom;
}
public List Deaggregate(List aggregatedObjects)
{
return deaggregator.Deaggregate(objects, this.aggregationInfo);
}
}
然后,聚合器的单元测试可以像这样工作:
var systemUnderTest = new Aggregator(new MockAggregator(), new MockDeaggragator());
这将允许您验证Aggregator
是否会为IAggregator
和IDeaggragotor
提供正确的参数。
最后,您还可以在单独的单元测试中测试RealDeaggragotor
,这才是满足您问题的。
不确定为什么您的聚合器需要知道这些信息,这不应该是聚合返回值的属性吗?
public static class Aggregator
{
public static AggregatedList Aggregate(List objects)
{
// aggregate objects to aggregatedlist and set the aggregationInfo
}
public static List Deaggregate(AggregatedList aggregatedList)
{
// use info from the aggregatedList
}
}
public class AggregatedList
{
public AggregationInfo AggregationInfo { get; set; }
public List AggregatedObjects { get; set; }
}