ArgumentException when creating new Faker on derived class with property using the 'new' modifier
I stumbled upon this issue when doing refactoring of our class hierarchies. The problem occurred when we introduced a few new base classes that have derived subclasses that use the 'new' modifier on a property.
We are running this on .NET 4.6.2 and Bogus 12.0.1. I have managed to reproduce the issue with the unit test below.
[TestClass]
public class BogusTest
{
[TestMethod]
public void TestMethod1()
{
//Works
var baseA = new Faker<BaseA>();
//Throws System.ArgumentException: 'An item with the same key has already been added.'
var derivedA = new Faker<DerivedA>();
}
}
class BaseA
{
public BaseB SomeProp { get; set; }
}
class DerivedA : BaseA
{
public new DerivedB SomeProp { get; set; }
}
class BaseB
{
public int Value { get; set; }
}
class DerivedB : BaseB
{
public new int Value { get; set; }
}
Hi @carleberg ,
Thanks very much for reporting this. I think I might have forgotten a binding flag that caused multiple properties (with the same name/key) being added into a dictionary.
I think I've made the correct fix and here's the passing unit test:
public class Issue70 : SeededTest
{
[Test]
public void should_be_able_to_create_derrived_faker_with_class_hierarchy()
{
var baseBFaker = new Faker<BaseB>()
.RuleFor(b => b.Value, f => f.Random.Int(1,5));
var derivedBFaker = new Faker<DerivedB>()
.RuleFor(b => b.Value, f => f.Random.Int(6,10)); ;
//Works
var baseAFaker = new Faker<BaseA>()
.RuleFor(a => a.SomeProp, () => baseBFaker.Generate()); ;
//Threw System.ArgumentException: 'An item with the same key has already been added.'
var derivedAFaker = new Faker<DerivedA>()
.RuleFor(da => da.SomeProp, () => derivedBFaker.Generate());
DerivedA derivedA = derivedAFaker.Generate();
derivedA.SomeProp.Value.Should().BeInRange(6,10);
BaseA baseA = derivedA;
baseA.SomeProp.Should().BeNull();
}
}
Let me know if the unit test above looks correct and I'll run a new release with the fix.
Thanks, :dash: :walking: "Bubbles of gas in my brain... Send me off balance, it's not enough"
Hi @carleberg ,
Bogus v15.0.1 is now available and should hopefully fix your issue. Let me know. Feel free to re-open the issue if you continue to have problems.
Thanks, Brian
:walking: :sunglasses: "So don't delay... act now supplies are running out..."
It works great, thanks a lot for your quick response!