Don’t Expose IList Just So You Can Assert Against Its Contents
Lately I’ve been trying to return IEnumerable
With tools like Resharper, It’s easy to change the return types of the methods that you’re getting the collection from and use an IList
The good news is that there’s a super simple solution to this situation that does not require changing the IEnumerable
1: IEnumerable<MyObject> myEnumerator = someService.GetStuff();
2: var myCollection = new List<MyObject>(myEnumerator);
3:
4: [Test]
5: public void my_test()
6: {
7: myCollection.Count.ShouldBe(1);
8: myCollection[0].ShouldEqual(myObject);
9: //etc.
10: }
</div> </div>
If you’re doing interaction testing with an interface and a mock object, where the interface receives an IEnumerable
</div> </div>
I can grab the output of this method via a stub and convert it to an IList
</div> </div>
Line 5 wraps up the IEnumerable
Now you never need to worry about whether you can test the IEnumerable 1: void ShowProductCodes(IEnumerable<Lookup> productCodes);
1: var view = Mock<IAssetClassificationView>();
2: view.Stub(v => v.ShowProductCodes(Arg<IEnumerable<Lookup>>.Is.Anything))
3: .Callback((IEnumerable<Lookup> lookups) =>
4: {
5: DisplayedProductCodes = new List<Lookup>(lookups);
6: return true;
7: });
8: return view;