简体   繁体   中英

How to customize DateTime format for AutoFixture?

I currently have a Model class Product:

public class ProductModel
{ 
  public string? ProductName{ get; set; }
  public DateTime ExpiryDate { get; set; }
}

I am using XUnit and AutoFixture for unit testing:

Below is my test method:

[Theory, AutoData]
public async Task SaveProduct_ShouldSaveProductToDatabase(ProductModel productModel)
{
  var expiry = productModel.ExpiryDate; // 2020-03-17 03:01:27.2166623
  ... implementation to save to database
}

Autofixture is used to autogenerate the date and this is set to 2020-03-17 03:01:27.2166623. Is there a way to customize ProductModel to return a model property in a specific format. For instance I want date returned to be set as 2020-03-17 03:01:27 (Without milliseconds).

I have searched for examples and found one that retrieves specific dates:

public class AllProducts2020: ICustomization
{
    public void Customize(IFixture fixture)
    {
        fixture.Customize<ProductModel>(composer =>
        composer.With(p => p.ExpiryDate, new DateTime(2020, 1, 1)));
    }
}

The above actually returns all product where date year is 2020. I want to use the Custom class like above, except that I return all products with dateformat like this:2020-03-17 03:01:27 (Without milliseconds)

Any hint of how this can be achieved?

Assuming you are familiar with AutoFixture customization you can always try to create your own DateTime sequence generator (ie ISpecimenBuilder ).

By default AutoFixture uses a random number generator to generate the total ticks value for the DateTime (see RandomDateTimeSequenceGenerator ). Since we know how many ticks there are in a second ( TimeSpan.TicksPerSecond ). you can try to add/subtract the ticks delta, to round the value in the desired direction.

Once you're done with the specimen builder, customize your Fixture instance with it and you should have DateTime values rounded up to a second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM