[英]How to generate default UTC DateTime when using AutoFixture and AutoData?
I have a Model class as below:我有一个 Model class 如下:
public class Students
{
public string FirstName {get;set;}
public string LastName {get;set;}
public DateTime DateJoined {get;set;}
}
I am then using AutoFixture
and AutoData
to generate random students:然后我使用AutoFixture
和AutoData
生成随机学生:
[Theory, AutoData]
public async Task Save_ShouldCreateStudent(Student student]
{
var createdStudent = student;
var createdStudentJoined = student.DateJoined; // This is in local date time format
}
The date created is not in UTC.创建的日期不是 UTC。 I want to configure Autofixture
to generate all datetimes in utc format by default.我想将Autofixture
配置为默认以 utc 格式生成所有日期时间。
During my research, I found the below example, but it is not valid for me, as it is using Fact and creates an instance of fixture.在我的研究过程中,我发现了以下示例,但它对我无效,因为它使用 Fact 并创建了一个夹具实例。 I want the datetime to be generated in UTC when I use Autodata and the value is generated from the classed passed in the method parameter itself.当我使用 Autodata 时,我希望在 UTC 中生成日期时间,并且该值是从方法参数本身中传递的类生成的。
Note: Below code is from my research and does not help me.注意:以下代码来自我的研究,对我没有帮助。 I am looking for a way to autogenerate UTC from my code above for Student.DateJoined
.我正在寻找一种从我上面的代码中为Student.DateJoined
自动生成 UTC 的方法。
public class UtcConverter : ISpecimenBuilder
{
private readonly ISpecimenBuilder builder;
public UtcConverter(ISpecimenBuilder builder)
{
this.builder = builder;
}
public object Create(object request, ISpecimenContext context)
{
var t = request as Type;
if (t == null && t != typeof(DateTime))
return new NoSpecimen(request);
var specimen = this.builder.Create(request, context);
if (!(specimen is DateTime))
return new NoSpecimen(request);
return ((DateTime)specimen).ToUniversalTime();
}
[Fact]
public void ResolveUtcDate()
{
var fixture = new Fixture();
fixture.Customizations.Add(
new UtcConverter(
new RandomDateTimeSequenceGenerator()));
var dt = fixture.Create<DateTime>();
Assert.Equal(DateTimeKind.Utc, dt.Kind);
}
}
Sounds like you want to create your own AutoDataAttribute
听起来您想创建自己的AutoDataAttribute
public class AutoDomainDataAttribute : AutoDataAttribute
{
public AutoDomainDataAttribute ()
: base(() => new Fixture().Customize(new MyDomainDataCustomization()))
{
}
}
where MyDomainDataCustomization
is a customization that encapsulates adding your specification builders其中MyDomainDataCustomization
是封装添加规范构建器的自定义
public class MyDomainDataCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customizations.Add(
new UtcConverter(
new RandomDateTimeSequenceGenerator()));
}
}
So now you can decorate the test with your AutoData attribute.所以现在你可以用你的 AutoData 属性来装饰测试。
[Theory]
[AutoDomainData]
public void ResolveUtcDate(DateTime dt)
{
Assert.Equal(DateTimeKind.Utc, dt.Kind);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.