簡體   English   中英

Autofixture可以枚舉所有給定每個屬性的可能值列表的對象

[英]Can Autofixture enumerate all objects given a list of possible values for each property

我正處於TDD的中間,可以根據屬性過濾對象。 過濾規則很多,每個都經常考慮多個屬性。

我開始檢查每個規則,通過提供它們被過濾的所有對象屬性的枚舉,但這很快就變得無趣了,我想解決在我的大腦被“復制 - 粘貼degenerescence”吃掉​​之前的痛苦。

AutoFixture在這種情況下應該非常有用,但我無法在FAQ或CheatSheet中找到這些信息。 Ploeh的博客填充列表看起來很有前景,但對我來說不夠深入。

所以,給出以下課程

public class Possibility
{
    public int? aValue {get;set;}
    public int? anotherValue {get;set;}
}

我可以得到一個Possibility列表,其中每個類包含一個可能的預定義值aValueanotherValue枚舉? 例如,給定的值[null, 10, 20]對於aValue[null, 42]anotherValue ,我將被返回的實例6 Possibility

如果不是,我怎么能在每個對象類型自己編碼之外得到這種行為?

鑒於問題的價值:

  • null1020aValue
  • null42--對於anotherValue

以下是使用Generator<T>進行AutoFixture的一種方法:

[Fact]
public void CustomizedAutoFixtureTest()
{
    var fixture = new Fixture();
    fixture.Customizations.Add(
        new PossibilityCustomization());

    var possibilities = 
        new Generator<Possibility>(fixture).Take(3);

    // 1st iteration
    // -------------------
    // aValue       | null
    // anotherValue | null 

    // 2nd iteration
    // -------------------
    // aValue       | 10
    // anotherValue | 42

    // 3rd iteration
    // -------------------
    // aValue       | 20
    // anotherValue | (Queue is empty, generated by AutoFixture.)
}

在內部, PossibilityCustomization使用Queue類提供預定義值 - 當它用完預定義值時,它使用AutoFixture。

private class PossibilityCustomization : ISpecimenBuilder
{
    private readonly Queue<int?> aValues = 
                 new Queue<int?>(new int?[] { null, 10, 20 });

    private readonly Queue<int?> anotherValues =
                 new Queue<int?>(new int?[] { null, 42 });

    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;
        if (pi != null)
        {
            if (pi.Name == "aValue" && aValues.Any())
                return aValues.Dequeue();

            if (pi.Name == "anotherValue" && anotherValues.Any())
                return anotherValues.Dequeue();
        }

        return new NoSpecimen();
    }
}

AutoFixture會生成匿名值 ,因此當您已經擁有要組合的精確值時,它可能不是完全適合該作業的正確工具。

如果你在NUnit上,你可以這樣做:

[Test]
public void HowToGetPermutations(
    [Values(null, 10, 20)] int? aValue,
    [Values(null, 42)] int? anotherValue)
{
    // Test and assert
}

這將運行此測試方法六次 - 每次可能的排列一次。

這是我希望xUnit.net擁有的為數不多的功能之一,但它沒有......

暫無
暫無

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

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