Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock ObservableCollection

I have the following:

class foo : ObservableCollection<Int32>
{
  //Stuff
}


[Test]
public void test()
{
  var foo = Mock.Of<foo>();
  int count = 0;
  Mock.Get(foo).Setup(x => x.Add(It.IsAny<Int32>())).Callback(() => count++);
  Mock.Get(foo).Setup(x => x.Count).Returns(() => count);
  //Do Stuff
}

However, Add and Count and especially the indexer[] are not overrideable. Is my only recourse, to create Addfoo that calls Add in my foo class, etc?

like image 841
Justin Pihony Avatar asked Jun 07 '26 16:06

Justin Pihony


1 Answers

I don't think you should mock such base types as List, ObservableCollection, or DateTime (even if it was possible). They are reliable and unlikely to change. Simply use ObservableCollection in your test instead of trying to re-implement it's count-increasing functionality. You always can do state-based verification:

var items = new ObservableCollection<int>();
// Do stuff
Assert.That(items.Count, Is.EqualTo(5));

If you are using your custom type Foo which is inherited from ObservableCollection<Int32> then you can also implement some IFoo interface which will be easy to mock:

public class Foo : ObservableCollection<Int32>, IFoo
like image 61
Sergey Berezovskiy Avatar answered Jun 10 '26 07:06

Sergey Berezovskiy