C# AutoFixture AutoMoq将项目添加到ObservableCollection不会引发CollectionChanged事件
我刚刚开始使用C# AutoFixture AutoMoq将项目添加到ObservableCollection不会引发CollectionChanged事件,c#,unit-testing,moq,autofixture,C#,Unit Testing,Moq,Autofixture,我刚刚开始使用AutoFixture,我现在很享受这些功能。但我刚刚创建了一个markseemann描述的automoqdata属性 但是现在我试图模拟一个对象,该对象包含一个ObservableCollection项,在我的Sut中,我订阅了CollectionChanged事件,并在添加新项时进行处理 我的Sut看起来像: public class Foo { public Foo(IBar barWithObservableCollection) { bar
AutoFixture
,我现在很享受这些功能。但我刚刚创建了一个markseemann描述的automoqdata属性
但是现在我试图模拟一个对象,该对象包含一个ObservableCollection
项,在我的Sut
中,我订阅了CollectionChanged
事件,并在添加新项时进行处理
我的Sut
看起来像:
public class Foo
{
public Foo(IBar barWithObservableCollection)
{
barWithObservableCollection.Items.CollectionChanged += this.OnItemsChanged;
}
public ObservableCollection<IFooThing> FooThings
{
get;
private set;
}
private void OnItemsChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
// Handle the new object and build a new IFooThing with it.
...
this.FooThings.Add(fooThing);
}
}
[Theory, AutoMoqData]
public void TestNewIBarThingsAreCorrectlyHandled([Frozen]IBar bar, [Frozen]IBarThing barThing, Foo sut)
{
bar.Items.Add(barThing);
Assert.Equal(1, sut.FooThings.Count);
}
因此,在我最初的测试实现中,为了确保处理了新项目,我使用Moq
对对象进行了完全模拟,并将所有内容绑定在一起(我将省略这一点,因为这对我的问题是不必要的)。但正如我所说的,我尝试使用AutoFixture
,现在我的测试如下所示:
public class Foo
{
public Foo(IBar barWithObservableCollection)
{
barWithObservableCollection.Items.CollectionChanged += this.OnItemsChanged;
}
public ObservableCollection<IFooThing> FooThings
{
get;
private set;
}
private void OnItemsChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
// Handle the new object and build a new IFooThing with it.
...
this.FooThings.Add(fooThing);
}
}
[Theory, AutoMoqData]
public void TestNewIBarThingsAreCorrectlyHandled([Frozen]IBar bar, [Frozen]IBarThing barThing, Foo sut)
{
bar.Items.Add(barThing);
Assert.Equal(1, sut.FooThings.Count);
}
所以我希望IBar.Items能自动设置一个observedcollection
,这是一个订阅的,也是一个。但是,当我调用bar.Items.Add
时,不会调用集合更改处理程序,尽管我可以看到IBar
对象上的Items
计数是递增的
有什么我做错了吗?如果我搞错了,我将不得不像以前一样手动设置集合,我宁愿不这样做,因为我喜欢更干净的语法
编辑:
在下面的评论之后,我检查了提供给测试的IBar
对象和提供给Sut
的对象是否相同,但结果表明它们不是相同的对象。我的印象是,[freezed]
属性指定每次请求该对象时,都会返回相同的对象引用?是bar
,实例传递给Foo
构造函数的是相同的对象\引用?啊,这看起来就像问题所在,IBar
(bar
object)在测试中,确实添加了项,但是存储在Foo
对象中的项没有在Add
之后添加。我认为freezed
属性指定在每个对Fixture
的请求中都会有相同的对象实例。根据这里给出的信息,我无法将代码发送到com请提供。