簡體   English   中英

單元測試耦合方法

[英]Unit testing coupled methods

在下面的示例中,如果無法設置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 ,通過調用具有不同List的Aggregation並在這些情況下驗證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);
    }
}

然后,您對Aggregator的單元測試可以像這樣工作:

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

這將允許您驗證Aggregator將為IAggregatorIDeaggragotor提供正確的參數。

最后,您還可以在單​​獨的單元測試中測試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; }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM