具有受保护构造函数和工厂方法的对象列表的自动fixture
本文关键字:对象 列表 fixture 方法 受保护 构造函数 工厂 | 更新日期: 2023-09-27 18:17:38
public partial class TestObjectCode
{
/// <summary>
/// We don't make constructor public and forcing to create object using
/// <see cref="Create"/> method.
/// But constructor can not be private since it's used by EntityFramework.
/// Thats why we did it protected.
/// </summary>
protected TestObjectCode() {}
public static TestObjectCode Create(
DateTime executiontime,
Int32 conditionid,
String conditionname)
{
var @objectToReturn = new TestObjectCode
{
ExecutionTime = executiontime,
ConditionId = conditionid,
ConditionName = conditionname
};
return @objectToReturn;
}
public virtual Int32 ConditionId { get; set; }
public virtual String ConditionName { get; set; }
public virtual DateTime ExecutionTime { get; set; }
}
测试:[Test]
[TestCase("1/1/2015", "07/5/2016")]
public void Task Should_Filter_By_Date_Range_Only(string startDate, string endDate)
{
//Arrange
var startDateTime = DateTime.Parse(startDate);
var endDateTime = DateTime.Parse(endDate);
//get randomDate between two Dates
TimeSpan timeSpan = endDateTime - startDateTime;
var randomTest = new Random();
TimeSpan newSpan = new TimeSpan(0, randomTest.Next(0, (int)timeSpan.TotalMinutes), 0);
DateTime newDate = startDateTime + newSpan;
var list = new List<TestObjectCode>();
_fixture.AddManyTo(list);
_fixture.Customize<TestObjectCode>(
c => c
.With(x => x.ExecutionTime, newDate)
.With(x => x.ConditionId, 1)
);
_fixture.RepeatCount = 7;
_fixture.AddManyTo(list);
}
以上测试由于_fixture而失败。定制和我的演员正在进行中。如果我把它公开,它就会起作用,但我想让它受到保护。这个类还有15个属性,我没有在这里列出。我还想在两个dateRanges之间为每个项目的列表随机日期。
如何调用工厂的Create方法?我需要为每个属性定义autoFixure吗?
Ploeh.AutoFixture。修饰的ISpecimenBuilder无法根据请求创建样本:EMR.Entities.AbpAuditLogs。如果请求表示接口或抽象类,则可能发生这种情况;如果是这种情况,注册一个ISpecimenBuilder,它可以根据请求创建样本。如果这种情况发生在强类型构建表达式中,请尝试使用IFactoryComposer方法之一来提供工厂。
您可以通过将.FromFactory(new MethodInvoker(new FactoryMethodQuery()))
添加到您的自定义中来使上述测试通过:
fixture.Customize<TestObjectCode>(
c => c
.FromFactory(new MethodInvoker(new FactoryMethodQuery()))
.With(x => x.ExecutionTime, newDate)
.With(x => x.ConditionId, 1));
这两个类都是在Ploeh.AutoFixture.Kernel
命名空间中定义的。
尽管如此,你还是应该重新考虑一下你的整体方法。