单元测试耦合方法

时间:2016-02-03 13:16:32

标签: c# unit-testing

在下面的示例中,如果我无法设置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 
    }
}

3 个答案:

答案 0 :(得分:1)

我会通过调用Aggregate然后调用Deaggregate来测试这一点,通过调用具有不同列表的聚合并在这些情况下验证Deaggregate中的预期行为来提供不同的方案

答案 1 :(得分:1)

如果您想确保仅对方法进行单元测试,则可以执行以下操作:

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);
    }
}

您对Aggregator的单元测试可以像以下一样工作:

var systemUnderTest = new Aggregator(new MockAggregator(), new MockDeaggragator());

这样您就可以验证Aggregator是否会为IAggregatorIDeaggragotor提供正确的参数。

最后,您还可以在单​​独的单元测试中测试RealDeaggragotor,这样可以满足您的问题。

答案 2 :(得分:0)

不确定为什么你的Aggregator需要知道这些信息,那不应该是Aggregate返回值的属性吗?

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; }
} 
相关问题