How do I tell Autofixture to create objects with different IDs?
I have a simple setup method in my tests that creates two object instances (make by and Id
and Description
) and I did it using autofixture:
MyObject o1 = fixture.Create<MyObject>();
MyObject o2 = fixture.Create<MyObject>();
Next I try to save objects to db but I get duplicate key error, I debug the installation and see that o1 and o2 have the same Id
According to the Wiki , the number should be generated progressively:
Autogenerated Number
int autoGeneratedNumber = fixture.Create<int>();
Sample Result
int: 1, followed by 2, then by 3, etc.
but it looks like id doesn't work that way with object property, so now I am using this workaround:
MyObject o1= fixture.Build<MyObject>().With(x => x.Id, 1).Create();
MyObject o2= fixture.Build<MyObject>().With(x => x.Id, 2).Create();
but I don't like it very much
here can be used ISpecimenBuilder
to configure Autofixture to make it generate progressive id?
Additional Information:
this is my base test class:
public class BaseDBTest
{
public BaseDBTest()
{ }
public Ploeh.AutoFixture.Fixture fixture { get { return new Fixture(); } }
}
and test setup:
[TestFixture]
public class MyObjectTests : BaseDBTest
{
MyObject o1;
MyObject o2;
[TestFixtureSetUp]
public void CreaDati()
{
o1= fixture.Create<MyObject >();
o2= fixture.Create<MyObject >();
}
}
weird things:
if i debug specific test objects created with different ids and random, but if i debug all tests of my project (with visual studio 2013 using Nunit runner) the ids are created equal
EDIT2
The definition of MyObject is quite complicated, sorry:
public class MyObject: LookUpObject<MyObject, int>
{
}
public abstract class LookUpObject<TObject, TKeyType> : EquatableObject<TObject>, IKeyedEntity<TKeyType>
where TObject : class
where TKeyType : struct
{
private TKeyType id;
private string description;
private bool isValid;
public virtual TKeyType Id
{
get { return id; }
set { id = value; }
}
public virtual string Description
{
get { return description; }
set { description= value; }
}
public virtual bool IsValid
{
get { return isValid; }
set { isValid= value; }
}
protected LookUpObject()
{
}
}
EDIT 3
a picture of strange things with Nunit (I was afraid it might depend on Visual Studio),
single test run link
trial run of the project link
source to share
This is because in the base class property you return a new Fixture object each time to get a Fixture. ID autogeneration can only be guaranteed for a Fixture instance.
Change this:
public class BaseDBTest
{
public BaseDBTest()
{ }
public Ploeh.AutoFixture.Fixture fixture { get { return new Fixture(); } }
}
:
public class BaseDBTest
{
private Fixture _fixture = new Fixture();
public BaseDBTest()
{ }
public Ploeh.AutoFixture.Fixture fixture { get { return _fixture; } }
}
source to share