{"id":1150,"date":"2017-06-12T11:35:02","date_gmt":"2017-06-12T11:35:02","guid":{"rendered":"http:\/\/tpodolak.com\/blog\/?p=1150"},"modified":"2017-06-14T10:49:11","modified_gmt":"2017-06-14T10:49:11","slug":"nsubstitute-returning-ienumerable","status":"publish","type":"post","link":"https:\/\/tpodolak.com\/blog\/2017\/06\/12\/nsubstitute-returning-ienumerable\/","title":{"rendered":"NSubstitute &#8211; returning value from IEnumerable"},"content":{"rendered":"<p>I&#8217;ve been using <i>NSubstitute<\/i> combined with automocks for quite some time already, but recently I&#8217;ve encountered quite interesting situation. Let&#8217;s assume that we have the following class we need to write tests for<\/p>\n<pre lang=\"csharp\">\r\npublic class PriceValidator : IValidator<Price>\r\n{\r\n    private readonly IEnumerable<IValidator<Price>> _innerValidators;\r\n\r\n    public PriceValidator(IEnumerable<IValidator<Price>> innerValidators)\r\n    {\r\n         _innerValidators = innerValidators;\r\n    }\r\n\r\n    public bool IsValid(Price input)\r\n    {\r\n        return _innerValidators.Any() && _innerValidators.All(validator => validator.IsValid(input));\r\n    }\r\n}\r\n<\/pre>\n<p>As mentioned before I wanted to test that class leveraging the concept of automocks. If you have never used them before, no worries, the idea is pretty simple. Instead of providing mock dependencies manually, you just generate them automatically. Once the dependencies are mocked you can retrieve and set them up if necessary. So in my case, I have to setup <i>IEnumerable&lt;IValidator&lt;Price&gt;&gt;<\/i> mock so that it yields some values. It can be achieved by mocking return values of <i>GetEnumerator()<\/i> method. <\/p>\n<pre lang=\"csharp\">\r\nvar automock = new NSubstituteAutoMocker<PriceValidator>();\r\nvar innerValidators = new List<IValidator<Price>>\r\n{\r\n    Substitute.For<IValidator<Price>>(),\r\n};            \r\nautomock.Get<IEnumerable<IValidator<Price>>>().GetEnumerator().Returns(innerValidators.GetEnumerator());\r\n<\/pre>\n<p>The entire test then can be written as<\/p>\n<pre lang=\"csharp\">\r\n[Fact]\r\npublic void IsValid_ReturnsTrue_WhenAllInnerValidatorsAreValid()\r\n{\r\n    var automock = new NSubstituteAutoMocker<PriceValidator>();\r\n    var innerValidators = new List<IValidator<Price>>\r\n    {\r\n        Substitute.For<IValidator<Price>>(),\r\n    };\r\n    innerValidators.ForEach(validator => validator.IsValid(Arg.Any<Price>()).Returns(true));\r\n    automock.Get<IEnumerable<IValidator<Price>>>().GetEnumerator().Returns(innerValidators.GetEnumerator());\r\n            \r\n    var result = automock.ClassUnderTest.IsValid(new Price());\r\n\r\n    innerValidators.ForEach(validator => validator.Received(1).IsValid(Arg.Any<Price>()));\r\n    result.Should().BeTrue();\r\n}\r\n<\/pre>\n<p>Everything looks good at that point, however if you run the tests, it will fail<br \/>\n<a href=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/FailedTest.png\" rel=\"attachment wp-att-1151\"><img decoding=\"async\" src=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/FailedTest.png\" alt=\"FailedTest\" width=\"900\" class=\"aligncenter size-full wp-image-1151\" srcset=\"https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/FailedTest.png 1338w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/FailedTest-150x49.png 150w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/FailedTest-300x97.png 300w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/FailedTest-1024x332.png 1024w\" sizes=\"(max-width: 1338px) 100vw, 1338px\" \/><\/a><br \/>\nThat was quite surprising for me and I have to admit that at the beginning I thought it was a bug in <i>NSubstitute<\/i>.<br \/>\nHowever, if you looks closely at the implementation of the test, you will see that every time validator collection is enumerated, the same instance of the enumerator is used. As the enumerator keeps its state, the first enumeration (<i>_innerValidators.Any()<\/i>) will move a current element to the first position (which is the last position at the same time) so when I try to enumerate again (<i>_innerValidators.All(validator => validator.IsValid(input)<\/i>) enumeration will continue from the previous position and the iteration will end yielding no results. Fortunately, with <i>NSubstitute<\/i> you can configure the call so that it always returns a new value. The relevant code changes are shown below<\/p>\n<pre>\r\nautomock.Get<IEnumerable<IValidator<Price>>>().GetEnumerator().Returns(callInfo => innerValidators.GetEnumerator());\r\n<\/pre>\n<p>Running the tests again will give us &#8220;green&#8221; result<br \/>\n<a href=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/Green.png\" rel=\"attachment wp-att-1152\"><img decoding=\"async\" src=\"\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/Green.png\" alt=\"Green\" width=\"900\" class=\"aligncenter size-full wp-image-1152\" srcset=\"https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/Green.png 1339w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/Green-150x49.png 150w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/Green-300x98.png 300w, https:\/\/tpodolak.com\/blog\/wp-content\/uploads\/2017\/06\/nsubstitute-returning-from-ienumerable\/Green-1024x335.png 1024w\" sizes=\"(max-width: 1339px) 100vw, 1339px\" \/><\/a><\/p>\n<p>Source code for this post can be found <a href=\"https:\/\/github.com\/tpodolak\/Blog\/tree\/master\/NSubstiuteReturningFromIEnumerable\">here<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve been using NSubstitute combined with automocks for quite some time already, but recently I&#8217;ve encountered quite interesting situation. Let&#8217;s assume that we have the following class we need to write tests for public class PriceValidator : IValidator { private readonly IEnumerable _innerValidators; public PriceValidator(IEnumerable innerValidators) { _innerValidators = innerValidators; } public bool IsValid(Price input) [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[326],"tags":[327],"class_list":["post-1150","post","type-post","status-publish","format-standard","hentry","category-nsubstitute","tag-nsubstitute"],"_links":{"self":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/1150","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/comments?post=1150"}],"version-history":[{"count":11,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/1150\/revisions"}],"predecessor-version":[{"id":1163,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/posts\/1150\/revisions\/1163"}],"wp:attachment":[{"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/media?parent=1150"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/categories?post=1150"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tpodolak.com\/blog\/wp-json\/wp\/v2\/tags?post=1150"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}