<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PGS Software &#187; mocking</title>
	<atom:link href="http://www.pgs-soft.com/tag/mocking/feed" rel="self" type="application/rss+xml" />
	<link>http://www.pgs-soft.com</link>
	<description>Nearshore Outsourcing IT Company - Offshore Development</description>
	<lastBuildDate>Fri, 30 Jul 2010 09:54:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Mocking ref and out method parameters in Moq</title>
		<link>http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html</link>
		<comments>http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html#comments</comments>
		<pubDate>Mon, 28 Jun 2010 07:00:47 +0000</pubDate>
		<dc:creator>Waldemar Mękal</dc:creator>
				<category><![CDATA[Developers]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips & trics]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.pgs-soft.com/?p=4194</guid>
		<description><![CDATA[Recently I had a situation, when I was writing an unit test and I need to mock a method with an &#8216;out&#8217; parameter. I had an import functionality where the import service was using a parser for processing input data before doing actual import. I wanted to test whether the import service handled errors from [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px; margin-top: 5px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.pgs-soft.com%2Fmocking-ref-and-out-method-parameters-in-moq.html"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.pgs-soft.com%2Fmocking-ref-and-out-method-parameters-in-moq.html&amp;source=pgssoftware&amp;style=normal&amp;service=bit.ly" height="61" width="50" /><br />
			</a>
		</div>
<p>Recently I had a situation, when I was writing an unit test and I need to mock a method with an &#8216;out&#8217; parameter. I had an import functionality where the import service was using a parser for processing input data before doing actual import. I wanted to test whether the import service handled  errors from the parser. The parser interface was as below.</p>
<pre>public interface IImportParser
{
  ImportRecord Parse(string data, out ErrorInfo[] errors);
}</pre>
<p>I was using Moq for mocking, so I did a quick look to docs and I did the following.</p>
<pre>var mock = new Mock&lt;IImportParser&gt;(MockBehavior.Strict);

var errors = new ErrorInfo[]
{
  new ErrorInfo(3, "Parse error at line 3.")
};
mock
  .Setup(x =&gt; x.Parse(It.IsAny&lt;string&gt;(), out errors))
  .Returns(new ImportRecord[]{ });
</pre>
<p>As you can see, mock was returning errors defined by me for any input for Parse() method, so it was what I looked for.</p>
<p>The same you can do for &#8216;ref&#8217; parameters.</p>
<p>Hope this helps!</p>
<hr /><small>Copyright &copy; 2004 - 2010 by <a href="http://www.pgs-soft.com">PGS Software</a>
<br/><br/>
<a href="http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html#comments">Comments (0)</a> - originally posted here <a href="http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html">http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html</a> </small>

<h2>Related posts</h2><ol><li><a href='http://www.pgs-soft.com/mocking-with-moq.html' rel='bookmark' title='Permanent Link: Mocking with Moq'>Mocking with Moq</a></li>
<li><a href='http://www.pgs-soft.com/parsing-csv-file-using-filehelpers-library.html' rel='bookmark' title='Permanent Link: Parsing CSV file using FileHelpers library'>Parsing CSV file using FileHelpers library</a></li>
<li><a href='http://www.pgs-soft.com/mocking-datetime-now.html' rel='bookmark' title='Permanent Link: Mocking DateTime.Now'>Mocking DateTime.Now</a></li>
</ol>]]></content:encoded>
			<wfw:commentRss>http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mocking with Moq</title>
		<link>http://www.pgs-soft.com/mocking-with-moq.html</link>
		<comments>http://www.pgs-soft.com/mocking-with-moq.html#comments</comments>
		<pubDate>Mon, 22 Jun 2009 11:26:19 +0000</pubDate>
		<dc:creator>Waldemar Mękal</dc:creator>
				<category><![CDATA[Developers]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[moq]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.pgs-soft.com/?p=2568</guid>
		<description><![CDATA[There are many mocking frameworks in the .NET world. Probably, the best known is Rhino Mocks. I used it and I found it a little tricky. I had to browse its documentation many times to find out how to do something. Recently, through some technical reading, I have found another mocking framework called Moq. What [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px; margin-top: 5px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.pgs-soft.com%2Fmocking-with-moq.html"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.pgs-soft.com%2Fmocking-with-moq.html&amp;source=pgssoftware&amp;style=normal&amp;service=bit.ly" height="61" width="50" /><br />
			</a>
		</div>
<p>There are many mocking frameworks in the .NET world. Probably, the best known is Rhino Mocks. I used it and I found it a little tricky. I had to browse its documentation many times to find out how to do something. Recently, through some technical reading, I have found another mocking framework called <a title="Moq" href="http://code.google.com/p/moq/" target="_blank">Moq</a>. What attracted my attention to it was really simple and intuitive api.</p>
<h3>Introduction</h3>
<p>Moq is pronounced as &#8220;Mock-you&#8221; or simple &#8220;Mock&#8221;. The current version is 3.1. 0.  It supports .NET 3.5, so you can use Linq and lambda expressions. All information you need to start working with it  can be found on its <a title="quick start page" href="http://code.google.com/p/moq/wiki/QuickStart" target="_blank">quick start page</a>.</p>
<p>In this post, I would like to shortly present Moq&#8217;s most useful features. All examples are taken from <a title="quick start page" href="http://code.google.com/p/moq/wiki/QuickStart" target="_blank">Moq quick start</a>.</p>
<h3>Creating a mock</h3>
<p>Imagine that we have an interface IFoo.</p>
<pre>public interface IFoo
{
    string Name { get; set; }
    string Execute(string arg);
}</pre>
<p>Imagine that we have a client of this interface and we want to test it. So, we need a mock. We use the &#8220;new&#8221; operator and type we want to mock to create it.</p>
<pre>var mock = new Mock&lt;IFoo&gt;();</pre>
<p>Now, we need a reference to mocked type. We get it in the following way:</p>
<pre>IFoo foo = mock.Object;</pre>
<p>Then, we pass it to the client.</p>
<h3>Setting up method expectations</h3>
<p>It&#8217;s time for setting up expectations. We use mock&#8217;s method Setup().</p>
<pre>mock.Setup(foo =&gt; foo.Execute("value1")).Returns("response1");
mock.Setup(foo =&gt; foo.Execute("value2")).Returns("response2");</pre>
<p>This will cause mock to return &#8220;response1&#8243; for &#8220;value1&#8243; and &#8220;response2&#8243; for &#8220;value2&#8243;. We might also setup expectation for any value of argument.</p>
<pre>mock.Setup(x =&gt; x.Execute(It.IsAny&lt;string&gt;)))
    .Returns((string s) =&gt; s.ToLower());</pre>
<p>To specify arguments more precisely, we might use methods of &#8220;It&#8221; class such as IsInRange(), IsRegex(), Is(). This is really powerful. Another interesting thing you can see here is lazy evaluation of return value and access to passed argument.</p>
<p>What is more, it is possible to setup exceptions to be thrown.</p>
<pre>mock.Setup(foo =&gt; foo.Execute("reset"))
    .Throws&lt;InvalidOperationException&gt;();
mock.Setup(foo =&gt; foo.Execute(""))
    .Throws(new ArgumentException("command"));</pre>
<p>Call to foo.Execute with argument &#8220;reset&#8221; will result in throwing an InvalidOperationException by mock, call  with argument &#8220;&#8221; will cause an ArgumentException to be thrown.</p>
<p>Last thing I want to show in this section is use of callbacks.</p>
<pre>mock.Setup(foo =&gt; foo.Execute("ping"))
    .Callback(() =&gt; Console.WriteLine("Before returns"))
    .Returns(true)
    .Callback(() =&gt; Console.WriteLine("After returns"));</pre>
<p>Callback() might be used before Returns() or after it or in both places as in the example above.</p>
<h3>Setting up properties</h3>
<p>Setting up expectations for property is also very straightforward.</p>
<pre>mock.Setup(foo =&gt; foo.Name).Returns("bar");</pre>
<p>Now, foo.Name returns value &#8220;bar&#8221;. We can also expect a setter invocation.</p>
<pre>mock.SetupSet(foo =&gt; foo.Name = "foo");</pre>
<p>If we want a property value to be tracked, we might use the snippet below.</p>
<pre>mock.SetupProperty(f =&gt; f.Name);</pre>
<p>This will cause storing value set to property, so the code below will pass.</p>
<pre>mock.SetupProperty(f =&gt; f.Name, "foo");

IFoo foo = mock.Object;
Assert.Equal("foo", foo.Name); //inital value == "foo"

foo.Name = "bar";
Assert.Equal("bar", foo.Name);//now value == "bar"</pre>
<p>We set up expectations. Now, time for verification.</p>
<h3>Verifying calls</h3>
<p>Many times we need to check if a method was called or an event was fired. Below, in the first line we are verifying if there was a call to Execute with argument &#8220;ping&#8221;. In the second line we test if call to Execute with any string argument occurred.</p>
<pre>mock.Verify(foo =&gt; foo.Execute("ping"));
mock.Verify(foo =&gt; foo.Execute(It.IsAny&lt;string&gt;()));</pre>
<p>Sometimes, we might want to check how many times the method was called. We use &#8220;Times&#8221; class  for this purpose.</p>
<pre>mock.Verify(foo =&gt; foo.Execute("ping"), Times.Never());
mock.Verify(foo =&gt; foo.Execute("ping"), Times.AtLeastOnce());</pre>
<p>We also might want to verify if a property was used.</p>
<pre>mock.VerifyGet(f =&gt; f.Name);
mock.VerifySet(foo =&gt; foo.Name);</pre>
<h3>Strict mocks, loose mocks</h3>
<p>By default, every mock we create behaves like &#8220;loose&#8221; mock. It means that every call to property or method, which was not set up, results in returning the default value. If we want to test it more precisely, we can use &#8220;strict&#8221; behavior. In this case, every unexpected call will cause an exception to be thrown.</p>
<pre>var mock = new Mock&lt;IFoo&gt;(MockBehavior.Strict);</pre>
<h3>Summary</h3>
<p>I made only a short preview of Moq possibilities. You can find further information on <a title="moq" href="http://code.google.com/p/moq/" target="_self">Moq homepage</a>. I would recommend reading the quick start, which I think provides all information necessary  to start working with the framework.</p>
<p>Moq in my opinion is extremely developer friendly. It has really nice syntax which helps to produce clean and readable code. Surely, I will try it in real development.</p>
<hr /><small>Copyright &copy; 2004 - 2010 by <a href="http://www.pgs-soft.com">PGS Software</a>
<br/><br/>
<a href="http://www.pgs-soft.com/mocking-with-moq.html#comments">Comments (0)</a> - originally posted here <a href="http://www.pgs-soft.com/mocking-with-moq.html">http://www.pgs-soft.com/mocking-with-moq.html</a> </small>

<h2>Related posts</h2><ol><li><a href='http://www.pgs-soft.com/mocking-ref-and-out-method-parameters-in-moq.html' rel='bookmark' title='Permanent Link: Mocking ref and out method parameters in Moq'>Mocking ref and out method parameters in Moq</a></li>
<li><a href='http://www.pgs-soft.com/mocking-datetime-now.html' rel='bookmark' title='Permanent Link: Mocking DateTime.Now'>Mocking DateTime.Now</a></li>
<li><a href='http://www.pgs-soft.com/new-features-in-nunit-2-5-part-2-testing-exceptions.html' rel='bookmark' title='Permanent Link: New features in NUnit 2.5. Part 2 &#8211; testing exceptions'>New features in NUnit 2.5. Part 2 &#8211; testing exceptions</a></li>
</ol>]]></content:encoded>
			<wfw:commentRss>http://www.pgs-soft.com/mocking-with-moq.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
