{"id":1613,"date":"2014-04-26T12:33:29","date_gmt":"2014-04-26T12:33:29","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=1613"},"modified":"2023-08-09T13:43:48","modified_gmt":"2023-08-09T13:43:48","slug":"comparing-moq-and-justmock-lite","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/comparing-moq-and-justmock-lite\/","title":{"rendered":"Comparing Moq and JustMock lite"},"content":{"rendered":"<p>This is not meant as a &#8220;which is best&#8221; post or even a feature blow by blow comparison but more a &#8220;I&#8217;m using JustMock lite (known henceforth as JML) how do I do this in Moq&#8221; or vice versa.<\/p>\n<p>Please note, MOQ version 4.20 has introduced a <a href=\"https:\/\/github.com\/moq\/moq\/releases\/tag\/v4.20.0\" rel=\"noopener\" target=\"_blank\">SponsoreLink<\/a> which appears to send data to some third party. See discussions on <a href=\"https:\/\/github.com\/moq\/moq\/issues\/1372\" rel=\"noopener\" target=\"_blank\">GitHub<\/a>. <\/p>\n<p>For this post I&#8217;m using Moq 4.2.1402.2112 and JML 20014.1.1424.1<\/p>\n<p><em>For the code samples, I&#8217;m writing xUnit tests but I&#8217;m not necessarily going to write code to use the mocks but will instead call directly on the mocks to demonstrate solely how they would work. Such tests would obviously only really ensure the mocking framework worked as expected, but hopefully the ideas of the mocks usage is conveyed in as little code as possible.<\/em><\/p>\n<p><strong>Strict behaviour<\/strong><\/p>\n<p>By default both Moq and JML use loose behavior meaning simply that if we do not create any Setup or Arrange code for methods\/properties being mocked, then the mocking framework will default them. When using strict behavior we are basically saying if a method or property is called on the mock object and we&#8217;ve not setup any behaviors for the mock object, then the mocking framework should fail &#8211; meaning we&#8217;ll get an exception from the mocking framework.<\/p>\n<p>Following is an example of using the strict behavior &#8211; removing the Setup\/Arrange will cause a mocking framework exception, adding the Setup\/Arrange will fulfill the strict behavior and allow the code to complete<\/p>\n<p><em>Using Moq<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nMock&lt;IFeed&gt; feed = new Mock&lt;IFeed&gt;(MockBehavior.Strict);\r\n\r\nfeed.Setup(f =&gt; f.GetTitle()).Returns(&quot;&quot;);\r\n\r\nfeed.Object.GetTitle();\r\n<\/pre>\n<p><em>Using JML<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nIFeed feed = Mock.Create&lt;IFeed&gt;(Behavior.Strict);\r\n\r\nMock.Arrange(() =&gt; feed.GetTitle()).Returns(&quot;&quot;);\r\n\r\nfeed.GetTitle();\r\n<\/pre>\n<p>Removing the MockBehavior.Strict\/Behavior.Strict from the mock calls will switch to loose behaviors.<\/p>\n<p><strong>Ensuring a mocked method\/property is called <em>n<\/em> times<\/strong><\/p>\n<p>Occasionally we want to ensure that a method\/property is called a specified number of times only, for example, once, at least <em>n<\/em> times, at most <em>n<\/em> etc. <\/p>\n<p><em>Using Moq<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nMock&lt;IFeed&gt; feed = new Mock&lt;IFeed&gt;();\r\n\r\nfeed.Setup(f =&gt; f.GetTitle()).Returns(&quot;&quot;);\r\n\r\nfeed.Object.GetTitle();\r\n\r\nfeed.Verify(f =&gt; f.GetTitle(), Times.Once);\r\n<\/pre>\n<p><em>Using JML<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nIFeed feed = Mock.Create&lt;IFeed&gt;();\r\n\r\nMock.Arrange(() =&gt; feed.GetTitle()).Returns(&quot;&quot;).OccursOnce();\r\n\r\nfeed.GetTitle();\r\n\r\nMock.Assert(feed);\r\n<\/pre>\n<p>In both examples we could change OccursOnce()\/Times.Once to OccursNever()\/Times.Never or Occurs(2)\/Times.Exactly(2) and so on.<\/p>\n<p><strong>Throwing exceptions<\/strong><\/p>\n<p>On occasion we may want to mock an exception, maybe our IFeed throws a WebException if it cannot download data from a website, we want to simulate this on our mock object -then we can use the following<\/p>\n<p><em>Using Moq<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nMock&lt;IFeed&gt; feed = new Mock&lt;IFeed&gt;();\r\n\r\nfeed.Setup(f =&gt; f.Download()).Throws&lt;WebException&gt;();\r\n\r\nAssert.Throws&lt;WebException&gt;(() =&gt; feed.Object.Download());\r\n\r\nfeed.Verify();\r\n<\/pre>\n<p><em>Using JML<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nIFeed feed = Mock.Create&lt;IFeed&gt;();\r\n\r\nMock.Arrange(() =&gt; feed.Download()).Throws&lt;WebException&gt;();\r\n\r\nAssert.Throws&lt;WebException&gt;(() =&gt; feed.Download());\r\n\r\nMock.Assert(feed);\r\n<\/pre>\n<p><strong>Supporting multiple interfaces<\/strong><\/p>\n<p>Occasionally we might be mocking an interface, such as IFeed but our application will check if the IFeed object also supports IDataErrorInfo (for example) and handle the code accordingly. So, without actually changing the IFeed what we would expect is a concrete class which implements both interfaces.<\/p>\n<p><em>Using Moq<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nMock&lt;IFeed&gt; feed = new Mock&lt;IFeed&gt;();\r\nfeed.As&lt;IDataErrorInfo&gt;();\r\n\r\nAssert.IsAssignableFrom(typeof(IDataErrorInfo), feed.Object);\r\n<\/pre>\n<p><em>Using JML<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nIFeed feed = Mock.Create&lt;IFeed&gt;(r =&gt; r.Implements&lt;IDataErrorInfo&gt;());\r\n\r\nAssert.IsAssignableFrom(typeof(IDataErrorInfo), feed);\r\n<\/pre>\n<p>As you can see, we add interfaces to our mock in Moq by using the As method and in JML using the Implements method, we can change these methods together to also add further interfaces to our mock as per <\/p>\n<p><em>Using Moq<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nMock&lt;IFeed&gt; feed = new Mock&lt;IFeed&gt;();\r\nfeed.As&lt;IDataErrorInfo&gt;().\r\n     As&lt;INotifyPropertyChanged&gt;();\r\n\r\nAssert.IsAssignableFrom(typeof(IDataErrorInfo), feed.Object);\r\nAssert.IsAssignableFrom(typeof(INotifyPropertyChanged), feed.Object);\r\n<\/pre>\n<p><em>Using JML<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nIFeed feed = Mock.Create&lt;IFeed&gt;(r =&gt; \r\n   r.Implements&lt;IDataErrorInfo&gt;().\r\n     Implements&lt;INotifyPropertyChanged&gt;());\r\n\r\nAssert.IsAssignableFrom(typeof(IDataErrorInfo), feed);\r\nAssert.IsAssignableFrom(typeof(INotifyPropertyChanged), feed);\r\n<\/pre>\n<p><strong>Automocking<\/strong><\/p>\n<p>One of the biggest problems when unit testing using mocks is when a system under test (SUT) requires many parts to be mocked and setup, or if the code for the SUT changes often, requiring refactoring of tests to simply add\/change etc. the mock objects used.<\/p>\n<p>As you&#8217;ve already seen with Loose behavior we can get around the need to setup every single bit of code and thus concentrate our tests on specific areas without creating a thousand and one mock&#8217;s and setup\/arrange sections of code. But in a possibly ever changing SUT it would be good if we didn&#8217;t need to continually add\/remove mocks which we might not be testing against.<\/p>\n<p>What would be nice is if the mocking framework could work like an IoC system and automatically inject the mocks for us &#8211; this is basically what auto mocking is about.<\/p>\n<p>So if we look at the code below, assume for a moment that initially the code didn&#8217;t include IProxySettings, we write our IFeedList mock and write the code to test the RssReader, now we add a new interface IProxySettings and now we need to alter the tests to include this interface even though our current test code doesn&#8217;t need it. Ofcourse with the addition of a single interface this may seem to be a little over the top, however it can easily get a lot worse.<\/p>\n<p>So here&#8217;s the code&#8230;<\/p>\n<p><em>System under test and service code<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic interface IFeedList\r\n{\r\n   string Download();\r\n}\r\n\r\npublic interface IProxySettings\r\n{\t\t\r\n}\r\n\r\npublic class RssReader\r\n{\r\n   private IFeedList feeds;\r\n   private IProxySettings settings;\r\n\r\n   public RssReader(IProxySettings settings, IFeedList feeds)\r\n   {\r\n      this.settings = settings;\r\n      this.feeds = feeds;\r\n   }\r\n\r\n   public string Download()\r\n   {\r\n      return feeds.Download();\r\n   }\r\n}\r\n<\/pre>\n<p>Now when the auto mocking container mocks the RssReader, it will automatically inject mocks for the two interfaces, then it&#8217;s up to our test code to setup or arrange expectations etc. on it.<\/p>\n<p><em>Using Moq<\/em><\/p>\n<p>Unlike the code you will see (further below) for JML, Moq doesn&#8217;t come with a auto mock container by default (JML NuGet&#8217;s package will add the Telerik.JustMock.Container by default). Instead Moq appears to have several auto mocking containers created for use with it by the community at large. I&#8217;m going to concentrate on Moq.Contrib which includes the AutoMockContainer class.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nMockRepository repos = new MockRepository(MockBehavior.Loose);\r\nAutoMockContainer container = new AutoMockContainer(repos);\r\n\r\nRssReader rss = container.Create&lt;RssReader&gt;();\r\n\r\ncontainer.GetMock&lt;IFeedList&gt;().Setup(f =&gt; f.Download()).Returns(&quot;Data&quot;);\r\n\r\nAssert.Equal(&quot;Data&quot;, rss.Download());\r\n\r\nrepos.VerifyAll();\r\n<\/pre>\n<p><em>Using JML<\/em><\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nvar container = new MockingContainer&lt;RssReader&gt;();\r\n\r\ncontainer.Arrange&lt;IFeedList&gt;(f =&gt; f.Download()).Returns(&quot;Data&quot;);\r\n\r\nAssert.Equal(&quot;Data&quot;, container.Instance.Download());\r\n\r\ncontainer.AssertAll();\r\n<\/pre>\n<p>In both cases the auto mock container created our RssReader, mocking the interfaces passed to it. <\/p>\n<p>That&#8217;s it for now, I&#8217;ll add further comparisons as and when I get time.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is not meant as a &#8220;which is best&#8221; post or even a feature blow by blow comparison but more a &#8220;I&#8217;m using JustMock lite (known henceforth as JML) how do I do this in Moq&#8221; or vice versa. Please note, MOQ version 4.20 has introduced a SponsoreLink which appears to send data to some [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[68,31],"tags":[],"class_list":["post-1613","post","type-post","status-publish","format-standard","hentry","category-justmock-lite","category-moq"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/1613","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=1613"}],"version-history":[{"count":5,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/1613\/revisions"}],"predecessor-version":[{"id":10070,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/1613\/revisions\/10070"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=1613"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=1613"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=1613"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}