簡體   English   中英

如何使用 AutoFixture 自定義集合

[英]How to use AutoFixture to customize a collection

我想開始使用 AutoFixture,但我確實對如何自定義集合有疑問。

給定以下 class:

public sealed class Contract
{
    public DateTime StartDate { get; set; }
}

我想使用 AutoFixture 的ISpecimenBuilder (或其他任何東西)來創建合同集合。

我想將日期/時間傳遞給我的樣本,因此,當我向 AutoFixture 詢問Contract實例的集合時,我想返回 3:

  • 1 帶有Start Date ,過去(基於我提供給 ISpecimen 的日期/時間)。

  • 1 帶有Start Date ,與當前日期匹配(基於我提供給 ISpecimen 的日期/時間)。

  • 1 帶有Start Date ,在未來(基於我提供給 ISpecimen 的日期/時間)。

在閱讀和玩過它之后,我相信我需要像種子這樣的東西,但我沒有得到任何工作,關於如何解決這個問題的任何建議?

使用這個答案,我嘗試使用后處理功能。 我認為這很接近。

創建命令以設置StartDate 我能找到傳遞“種子”日期的唯一方法是通過構造函數。 這里唯一需要解決的是如何知道你在集合中的位置並相應地設置日期。

public class SeedStartDateCommand : ISpecimenCommand
{
   private DateTime _seedDate;

   public SeedStartDateCommand(DateTime seedDate)
   {
      _seedDate = seedDate;
   }

   public void Execute(object specimen, ISpecimenContext context)
   {
      if (specimen is not Contract contract)
      {
         return;
      }

      // This is where you need to work out where you are in the 
      // collection. I.e. is this 0, -1 or +1?
      contract.StartDate = _seedDate;
   }
}

然后將其與夾具連接起來。 它非常冗長,因此可以隱藏在擴展方法中。 另外,我從另一個答案中獲取了該代碼,因此可能所有PostProcessor接線都不是必需的。

var fixture = new Fixture();

var seedDate = DateTime.UtcNow;

fixture.Customizations.Add(
   SpecimenBuilderNodeFactory.CreateTypedNode(
       typeof(Contract),
       new Postprocessor(
          new MethodInvoker(
             new ModestConstructorQuery()),
             new CompositeSpecimenCommand(
                new AutoPropertiesCommand(),
                new SeedStartDateCommand(seedDate)))));

var contracts = fixture.CreateMany<Contract>();

我不認為這是最終的解決方案,但它似乎接近......

暫無
暫無

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

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