AutoFixture是否支持.NET6的"DateOnly"



我在使用AutoFixture构造DateOnly变量/字段时遇到异常。(TimeOnly的构建效果良好(

AutoFixture.ObjectCreationExceptionWithPath:AutoFixture无法从System.DateOnly创建实例,因为创建意外失败,出现异常。请参阅内部异常以调查失败的根本原因。

AutoFixture,AutoFixture.NUnit3 nugets版本:4.17.0

using AutoFixture;
using AutoFixture.NUnit3;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class AutoFixtureCreateTests
{
private readonly Fixture fixture = new();
[SetUp]
public void Setup()
{
var date = fixture.Create<DateOnly>();  //fails
var time = fixture.Create<TimeOnly>();  //works fine
}
[Test, AutoData]
public void CreateString(string str) { } //works fine
[Test, AutoData]
public void CreateDateOnly(DateOnly date) { } //fails
[Test, AutoData]
public void CreateTimeOnly(TimeOnly time) { } //works fine
}
}

答案:目前没有。存在拉取请求:https://github.com/AutoFixture/AutoFixture/pull/1305(然而,它几乎一年都处于开放状态,没有任何里程碑(

但有一个变通办法。我的临时解决方案是创建AutoFixture自定义(CustomFixture.cs(文件,并将其包含在项目中:

using AutoFixture;
using AutoFixture.NUnit3;
namespace UnitTests
{
public class CustomFixture
{
public static Fixture Create()
{
var fixture = new Fixture();
fixture.Customize<DateOnly>(composer => composer.FromFactory<DateTime>(DateOnly.FromDateTime));
return fixture;
}
}
public class CustomAutoDataAttribute : AutoDataAttribute
{
public CustomAutoDataAttribute()
: base(()=>CustomFixture.Create())
{}
}
}

在测试代码中包含自定义之后:

using AutoFixture;
using AutoFixture.NUnit3;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class AutoFixtureCreateTests
{
private readonly Fixture fixture = 
CustomFixture.Create();  //custom factory
[SetUp]
public void Setup()
{
var date = fixture.Create<DateOnly>();  //now works
var time = fixture.Create<TimeOnly>();  
}
[Test, AutoData]
public void CreateString(string str) { } 
[Test, CustomAutoData] //custom attribute
public void CreateDateOnly(DateOnly date) { } //now works
[Test, AutoData]
public void CreateTimeOnly(TimeOnly time) { } 
}
}

没有,但将来可能会(见@Evgeny的回答(。在代码中实现它的一种方法是为dateonly和timeonly创建可重复使用的fixture自定义:

public class DateOnlyFixtureCustomization: ICustomization
{
void ICustomization.Customize(IFixture fixture)
{
fixture.Customize<DateOnly>(composer => composer.FromFactory<DateTime>(DateOnly.FromDateTime));
}
}
public class TimeOnlyFixtureCustomization: ICustomization
{
void ICustomization.Customize(IFixture fixture)
{
fixture.Customize<TimeOnly>(composer => composer.FromFactory<DateTime>(TimeOnly.FromDateTime));
}
}

然后,它们可以在创建新的固定装置时使用,如

var fixture = new Fixture().Customize(new CompositeCustomization(
new DateOnlyFixtureCustomization(),
new TimeOnlyFixtureCustomization()
// Add other fixture customizations as needed
));

相关内容

  • 没有找到相关文章

最新更新