<?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>Elegant Code &#187; Mock Objects</title>
	<atom:link href="http://elegantcode.com/tag/mock-objects/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Partial Mocks explained</title>
		<link>http://elegantcode.com/2008/04/08/partial-mocks-explained/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=partial-mocks-explained</link>
		<comments>http://elegantcode.com/2008/04/08/partial-mocks-explained/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:14:42 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/08/partial-mocks-explained/</guid>
		<description><![CDATA[If you are wondering what is prompting this post, it is the fact that on my last post I got schooled by Jeff Brown of Bits-in-Motion.&#160;&#160; Jeff is also one of the minds behind Gallio and MBUnit.&#160; You can only hope to be told you are completely wrong by such a guy. He was very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are wondering what is prompting this post, it is the fact that on my <a href="http://elegantcode.com/2008/04/07/mocking-nested-methods/">last post</a> I got schooled by Jeff Brown of <a href="http://blog.bits-in-motion.com/">Bits-in-Motion</a>.&nbsp;&nbsp; Jeff is also one of the minds behind <a href="http://www.gallio.org">Gallio</a> and <a href="http://www.mbunit.com/">MBUnit</a>.&nbsp; You can only hope to be told you are completely wrong by such a guy. He was very nice about it actually, just stating a preference for a different way of handling the same problem.&nbsp; My problem was that his solution was better than mine.&nbsp; Much better.</p> <p>Where it led me was to re-investigate <a href="http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx">Partial Mocks in Rhino Mocks</a>.&nbsp; My original misunderstanding of Partial Mocks was that they would only mock Abstract Classes.&nbsp; A partial mock will mock ANY class -- but only the Partial mock will only mock abstract methods.&nbsp; That small misunderstanding has caused me to loose untold amount of hair and good will towards all men.</p> <p>So I'm going to re-implement my class methods.&nbsp; Here you go:</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyClass
{
    <span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
    {
        <span class="rem">// stuff happens here</span>
        <span class="kwrd">int</span> i = Bar();
        <span class="rem">// do more stuff here    </span>
        <span class="kwrd">return</span> i + 5;
    }
    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">int</span> Bar()
    {
       <span class="rem">// do some logic</span>
       <span class="kwrd">return</span> 1;
    }
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
A few changes here.&nbsp; First, I removed the delegate and renamed BarInternal back to <strong>Bar</strong>.&nbsp; Second, I marked the <strong>Bar</strong> method as <a href="http://msdn2.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx">virtual</a>.&nbsp; </p>
<p>They key point about a virtual method is that you can provide an implementation, and then a inherited class can completely override that method.&nbsp; That is what the Partial Mock is allowing us to do.</p>
<p>So how do I write my tests?&nbsp; If you don't like using Rhino Mocks you do this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    <span class="kwrd">int</span> expected = 7;
    <span class="kwrd">int</span> result = 0;
    MockRepository mock = <span class="kwrd">new</span> MockRepository();
    MyClass c = mock.PartialMock&lt;MyClass&gt;();

    <span class="kwrd">using</span> (mock.Record())
    {
        Expect.Call(c.Bar()).Return(2);
    }
    <span class="kwrd">using</span> (mock.Playback())
    {
        result = c.Foo();
    }

    Assert.AreEqual(expected, result);
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
Obviously, now my test is referencing the Rhino Mocks library.&nbsp; The variable mock is the Mock Repository.&nbsp; Now the big change is that I don't create MyClass directly, but through the Rhino Mocks PartialMock method.</p>
<p>Next, I tell the mock repository to expect a call to <strong>c.Bar</strong>, and when called return <strong>2</strong>.&nbsp; That is what is happening in the using (<strong>mock.Record()</strong>) section of the code.&nbsp; Then, in the <strong>mock.Playback</strong> section, I call <strong>Foo().</strong></p>
<p>One other quick note, if we were to rewrite <strong>Foo</strong> such that it no longer called <strong>Bar</strong> this test will fail.&nbsp; The <strong>Expect.Call</strong> part tell the mock repository that the method <strong>Bar</strong> will be called, and if it isn't there is a problem.&nbsp; There are ways around that as well, but that is a topic for another day.</p>
<p>Where does that leave us now?&nbsp; Aside from the odd "<strong>virtual</strong>" keyword thrown into our production code, this is the code as you would have originally written it, even without TDD.&nbsp; I don't like making API changes just to satisfy testing, but I am very OK with this change.</p>
<p>&nbsp;</p>
<p>But what about that new kid on the block?&nbsp; You know, <a href="http://code.google.com/p/moq/">Moq</a>.</p>
<p>I still love Rhino Mocks, but I can't help but want to play with a new toy.&nbsp; So here is the same thing, but in Moq:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_moq_test()
{
    Mock&lt;MyClass&gt; mock = <span class="kwrd">new</span> Mock&lt;MyClass&gt;();
    mock.Expect(x =&gt; x.Bar()).Returns(2);

    MyClass c = mock.Object;
    <span class="kwrd">int</span> result = c.Foo();
    Assert.AreEqual(7, result);
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>

<p>So as you should be able to see, Moq is a very different animal than RhinoMocks.&nbsp; There is no Record or Playback (the web site calls those confusing, I disagree, but still), and the <strong>Expect</strong> happens with a anonymous delegate (in the form of the Lambda Expression "<strong>x =&gt; x.Bar()</strong>" where x is of type <strong>MyClass</strong>).</p>
<p>The cool part is that you can get the same results with less code using Moq.&nbsp; That has been the main advantage all along.&nbsp; My informal testing also reveals that Moq is just a hair faster than Rhino Mocks (but not fast enough to warrant switching frameworks).</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/08/partial-mocks-explained/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Mocking nested methods</title>
		<link>http://elegantcode.com/2008/04/07/mocking-nested-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mocking-nested-methods</link>
		<comments>http://elegantcode.com/2008/04/07/mocking-nested-methods/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 02:16:09 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing/QA]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/07/mocking-nested-methods/</guid>
		<description><![CDATA[I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&#160; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&#160; Which probably means it is a bad idea.&#160; After all, if the Internet, [...]]]></description>
			<content:encoded><![CDATA[  <p>I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&nbsp; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&nbsp; Which probably means it is a bad idea.&nbsp; After all, if the Internet, the keeper of all that is right and true, doesn't know about something it must be wrong.</p> <h2>The problem</h2> <p>You have two methods (Foo and Bar), and Foo calls method Bar.&nbsp; It will look like this:</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here<br></span>&nbsp;&nbsp;&nbsp; return i + 5<br>}

<span class="kwrd">public</span> <span class="kwrd">int</span> Bar()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>Now you need to test both methods.&nbsp; Bar can be easily tested like this (this should work for NUnit and MBUnit tests -- assuming both methods exist in a class call MyClass):</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Bar_Test()
{
    MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Bar();
   Assert.AreEqual(1, result);
}</pre>
<p>Now we test Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_Test()
{
   MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Foo();
   Assert.AreEqual(6, result);
}</pre>
<p>Here is where we have an issue.&nbsp; What if the result of Bar changes?&nbsp; That will break the test.&nbsp; So now we have a brittle test.&nbsp; Any time Bar changes, we have to change all of the Bar tests, but also the Foo tests, so we have added complexity to our tests as well.&nbsp; Now if Foo (or Bar) was in a separate class, this wouldn't be an issue, but they are in the same class.&nbsp; And as much as I like small classes, this seems too trivial to split up (even in the context of an extremely trivial example). </p>
<h2>The Solution</h2>
<p>What I would like to do is Mock the method Bar.&nbsp; You can do that with a delegate.</p>
<p>Without really getting into what a delegate is, I will just show the code.&nbsp; So here are my two methods, with a delegate added in for good measure.</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">int</span> BarDelegate();

<span class="kwrd">public</span> BarDelegate Bar;

<span class="kwrd">public</span> MyClass()
{
    Bar = BarInternal;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here    </span>
    <span class="kwrd">return</span> i + 5;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> BarInternal()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>OK, here is what I did:</p>
<ol>
<li>Renamed Bar to BarInternal 
<li>BarDelegate delegate 
<li>Created a variable named Bar to point to the method BarInternal 
<li>Created a constructor to hook up Bar to BarInternal.</li></ol>
<p>Now all of my code can still use the method Bar just like it was there, but in actuality it is calling BarInternal.&nbsp; I have now created one layer of indirection to my method Bar so it can now be mocked and tested.</p>
<p>Here is my new test for Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = BarMethodForTest;
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}

<span class="kwrd">private</span> <span class="kwrd">int</span> BarMethodForTest()
{
    <span class="kwrd">return</span> 2;
}</pre>
<p>So what is new with the test is the BarMethodForTest that is passed to c.Bar and I have coded BarMethodForTest to always return 2.&nbsp; When I set c.Bar to my new method, BarInternal (the default method) is no longer called.</p>
<p>Actually, if I wanted to I could simplify this further by setting c.Bar with an anonymous delegate like this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = <span class="kwrd">delegate</span>() { <span class="kwrd">return</span> 2; }
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}</pre>
<h2>Stepping Back</h2>
<p>OK, take a step back and look at this again with a critical eye.&nbsp; Have I really solved the problem?&nbsp;&nbsp; Yes and no.&nbsp; The real problem was that my methods were too complex to simply test.&nbsp; Now my methods are simple to test, but the code is complex to read.&nbsp; All I've done is shifted the complexity from one class to the other.&nbsp; A better solution would to have created another class and further abstracted out the logic.</p>
<p>At the same time, my class is not overly burdened by the change either.&nbsp; In lieu of a real refactoring, I do consider this a viable solution to the problem.&nbsp; So by all means do this -- but make sure you are out of alternatives first.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/07/mocking-nested-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rhino Mocks presentation &#8211; version 3.3</title>
	<atom:link href="http://elegantcode.com/tag/mock-objects/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Elegant Code &#187; Mock Objects</title>
	<atom:link href="http://elegantcode.com/tag/mock-objects/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Partial Mocks explained</title>
		<link>http://elegantcode.com/2008/04/08/partial-mocks-explained/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=partial-mocks-explained</link>
		<comments>http://elegantcode.com/2008/04/08/partial-mocks-explained/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:14:42 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/08/partial-mocks-explained/</guid>
		<description><![CDATA[If you are wondering what is prompting this post, it is the fact that on my last post I got schooled by Jeff Brown of Bits-in-Motion.&#160;&#160; Jeff is also one of the minds behind Gallio and MBUnit.&#160; You can only hope to be told you are completely wrong by such a guy. He was very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are wondering what is prompting this post, it is the fact that on my <a href="http://elegantcode.com/2008/04/07/mocking-nested-methods/">last post</a> I got schooled by Jeff Brown of <a href="http://blog.bits-in-motion.com/">Bits-in-Motion</a>.&nbsp;&nbsp; Jeff is also one of the minds behind <a href="http://www.gallio.org">Gallio</a> and <a href="http://www.mbunit.com/">MBUnit</a>.&nbsp; You can only hope to be told you are completely wrong by such a guy. He was very nice about it actually, just stating a preference for a different way of handling the same problem.&nbsp; My problem was that his solution was better than mine.&nbsp; Much better.</p> <p>Where it led me was to re-investigate <a href="http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx">Partial Mocks in Rhino Mocks</a>.&nbsp; My original misunderstanding of Partial Mocks was that they would only mock Abstract Classes.&nbsp; A partial mock will mock ANY class -- but only the Partial mock will only mock abstract methods.&nbsp; That small misunderstanding has caused me to loose untold amount of hair and good will towards all men.</p> <p>So I'm going to re-implement my class methods.&nbsp; Here you go:</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyClass
{
    <span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
    {
        <span class="rem">// stuff happens here</span>
        <span class="kwrd">int</span> i = Bar();
        <span class="rem">// do more stuff here    </span>
        <span class="kwrd">return</span> i + 5;
    }
    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">int</span> Bar()
    {
       <span class="rem">// do some logic</span>
       <span class="kwrd">return</span> 1;
    }
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
A few changes here.&nbsp; First, I removed the delegate and renamed BarInternal back to <strong>Bar</strong>.&nbsp; Second, I marked the <strong>Bar</strong> method as <a href="http://msdn2.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx">virtual</a>.&nbsp; </p>
<p>They key point about a virtual method is that you can provide an implementation, and then a inherited class can completely override that method.&nbsp; That is what the Partial Mock is allowing us to do.</p>
<p>So how do I write my tests?&nbsp; If you don't like using Rhino Mocks you do this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    <span class="kwrd">int</span> expected = 7;
    <span class="kwrd">int</span> result = 0;
    MockRepository mock = <span class="kwrd">new</span> MockRepository();
    MyClass c = mock.PartialMock&lt;MyClass&gt;();

    <span class="kwrd">using</span> (mock.Record())
    {
        Expect.Call(c.Bar()).Return(2);
    }
    <span class="kwrd">using</span> (mock.Playback())
    {
        result = c.Foo();
    }

    Assert.AreEqual(expected, result);
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
Obviously, now my test is referencing the Rhino Mocks library.&nbsp; The variable mock is the Mock Repository.&nbsp; Now the big change is that I don't create MyClass directly, but through the Rhino Mocks PartialMock method.</p>
<p>Next, I tell the mock repository to expect a call to <strong>c.Bar</strong>, and when called return <strong>2</strong>.&nbsp; That is what is happening in the using (<strong>mock.Record()</strong>) section of the code.&nbsp; Then, in the <strong>mock.Playback</strong> section, I call <strong>Foo().</strong></p>
<p>One other quick note, if we were to rewrite <strong>Foo</strong> such that it no longer called <strong>Bar</strong> this test will fail.&nbsp; The <strong>Expect.Call</strong> part tell the mock repository that the method <strong>Bar</strong> will be called, and if it isn't there is a problem.&nbsp; There are ways around that as well, but that is a topic for another day.</p>
<p>Where does that leave us now?&nbsp; Aside from the odd "<strong>virtual</strong>" keyword thrown into our production code, this is the code as you would have originally written it, even without TDD.&nbsp; I don't like making API changes just to satisfy testing, but I am very OK with this change.</p>
<p>&nbsp;</p>
<p>But what about that new kid on the block?&nbsp; You know, <a href="http://code.google.com/p/moq/">Moq</a>.</p>
<p>I still love Rhino Mocks, but I can't help but want to play with a new toy.&nbsp; So here is the same thing, but in Moq:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_moq_test()
{
    Mock&lt;MyClass&gt; mock = <span class="kwrd">new</span> Mock&lt;MyClass&gt;();
    mock.Expect(x =&gt; x.Bar()).Returns(2);

    MyClass c = mock.Object;
    <span class="kwrd">int</span> result = c.Foo();
    Assert.AreEqual(7, result);
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>

<p>So as you should be able to see, Moq is a very different animal than RhinoMocks.&nbsp; There is no Record or Playback (the web site calls those confusing, I disagree, but still), and the <strong>Expect</strong> happens with a anonymous delegate (in the form of the Lambda Expression "<strong>x =&gt; x.Bar()</strong>" where x is of type <strong>MyClass</strong>).</p>
<p>The cool part is that you can get the same results with less code using Moq.&nbsp; That has been the main advantage all along.&nbsp; My informal testing also reveals that Moq is just a hair faster than Rhino Mocks (but not fast enough to warrant switching frameworks).</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/08/partial-mocks-explained/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Mocking nested methods</title>
		<link>http://elegantcode.com/2008/04/07/mocking-nested-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mocking-nested-methods</link>
		<comments>http://elegantcode.com/2008/04/07/mocking-nested-methods/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 02:16:09 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing/QA]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/07/mocking-nested-methods/</guid>
		<description><![CDATA[I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&#160; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&#160; Which probably means it is a bad idea.&#160; After all, if the Internet, [...]]]></description>
			<content:encoded><![CDATA[  <p>I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&nbsp; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&nbsp; Which probably means it is a bad idea.&nbsp; After all, if the Internet, the keeper of all that is right and true, doesn't know about something it must be wrong.</p> <h2>The problem</h2> <p>You have two methods (Foo and Bar), and Foo calls method Bar.&nbsp; It will look like this:</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here<br></span>&nbsp;&nbsp;&nbsp; return i + 5<br>}

<span class="kwrd">public</span> <span class="kwrd">int</span> Bar()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>Now you need to test both methods.&nbsp; Bar can be easily tested like this (this should work for NUnit and MBUnit tests -- assuming both methods exist in a class call MyClass):</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Bar_Test()
{
    MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Bar();
   Assert.AreEqual(1, result);
}</pre>
<p>Now we test Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_Test()
{
   MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Foo();
   Assert.AreEqual(6, result);
}</pre>
<p>Here is where we have an issue.&nbsp; What if the result of Bar changes?&nbsp; That will break the test.&nbsp; So now we have a brittle test.&nbsp; Any time Bar changes, we have to change all of the Bar tests, but also the Foo tests, so we have added complexity to our tests as well.&nbsp; Now if Foo (or Bar) was in a separate class, this wouldn't be an issue, but they are in the same class.&nbsp; And as much as I like small classes, this seems too trivial to split up (even in the context of an extremely trivial example). </p>
<h2>The Solution</h2>
<p>What I would like to do is Mock the method Bar.&nbsp; You can do that with a delegate.</p>
<p>Without really getting into what a delegate is, I will just show the code.&nbsp; So here are my two methods, with a delegate added in for good measure.</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">int</span> BarDelegate();

<span class="kwrd">public</span> BarDelegate Bar;

<span class="kwrd">public</span> MyClass()
{
    Bar = BarInternal;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here    </span>
    <span class="kwrd">return</span> i + 5;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> BarInternal()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>OK, here is what I did:</p>
<ol>
<li>Renamed Bar to BarInternal 
<li>BarDelegate delegate 
<li>Created a variable named Bar to point to the method BarInternal 
<li>Created a constructor to hook up Bar to BarInternal.</li></ol>
<p>Now all of my code can still use the method Bar just like it was there, but in actuality it is calling BarInternal.&nbsp; I have now created one layer of indirection to my method Bar so it can now be mocked and tested.</p>
<p>Here is my new test for Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = BarMethodForTest;
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}

<span class="kwrd">private</span> <span class="kwrd">int</span> BarMethodForTest()
{
    <span class="kwrd">return</span> 2;
}</pre>
<p>So what is new with the test is the BarMethodForTest that is passed to c.Bar and I have coded BarMethodForTest to always return 2.&nbsp; When I set c.Bar to my new method, BarInternal (the default method) is no longer called.</p>
<p>Actually, if I wanted to I could simplify this further by setting c.Bar with an anonymous delegate like this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = <span class="kwrd">delegate</span>() { <span class="kwrd">return</span> 2; }
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}</pre>
<h2>Stepping Back</h2>
<p>OK, take a step back and look at this again with a critical eye.&nbsp; Have I really solved the problem?&nbsp;&nbsp; Yes and no.&nbsp; The real problem was that my methods were too complex to simply test.&nbsp; Now my methods are simple to test, but the code is complex to read.&nbsp; All I've done is shifted the complexity from one class to the other.&nbsp; A better solution would to have created another class and further abstracted out the logic.</p>
<p>At the same time, my class is not overly burdened by the change either.&nbsp; In lieu of a real refactoring, I do consider this a viable solution to the problem.&nbsp; So by all means do this -- but make sure you are out of alternatives first.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/07/mocking-nested-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rhino Mocks presentation &#8211; version 3.3</title>
		<link>http://elegantcode.com/2008/04/08/partial-mocks-explained/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=partial-mocks-explained</link>
		<comments>http://elegantcode.com/2008/04/08/partial-mocks-explained/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:14:42 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/08/partial-mocks-explained/</guid>
		<description><![CDATA[If you are wondering what is prompting this post, it is the fact that on my last post I got schooled by Jeff Brown of Bits-in-Motion.&#160;&#160; Jeff is also one of the minds behind Gallio and MBUnit.&#160; You can only hope to be told you are completely wrong by such a guy. He was very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are wondering what is prompting this post, it is the fact that on my <a href="http://elegantcode.com/2008/04/07/mocking-nested-methods/">last post</a> I got schooled by Jeff Brown of <a href="http://blog.bits-in-motion.com/">Bits-in-Motion</a>.&nbsp;&nbsp; Jeff is also one of the minds behind <a href="http://www.gallio.org">Gallio</a> and <a href="http://www.mbunit.com/">MBUnit</a>.&nbsp; You can only hope to be told you are completely wrong by such a guy. He was very nice about it actually, just stating a preference for a different way of handling the same problem.&nbsp; My problem was that his solution was better than mine.&nbsp; Much better.</p> <p>Where it led me was to re-investigate <a href="http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx">Partial Mocks in Rhino Mocks</a>.&nbsp; My original misunderstanding of Partial Mocks was that they would only mock Abstract Classes.&nbsp; A partial mock will mock ANY class -- but only the Partial mock will only mock abstract methods.&nbsp; That small misunderstanding has caused me to loose untold amount of hair and good will towards all men.</p> <p>So I'm going to re-implement my class methods.&nbsp; Here you go:</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyClass
{
    <span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
    {
        <span class="rem">// stuff happens here</span>
        <span class="kwrd">int</span> i = Bar();
        <span class="rem">// do more stuff here    </span>
        <span class="kwrd">return</span> i + 5;
    }
    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">int</span> Bar()
    {
       <span class="rem">// do some logic</span>
       <span class="kwrd">return</span> 1;
    }
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
A few changes here.&nbsp; First, I removed the delegate and renamed BarInternal back to <strong>Bar</strong>.&nbsp; Second, I marked the <strong>Bar</strong> method as <a href="http://msdn2.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx">virtual</a>.&nbsp; </p>
<p>They key point about a virtual method is that you can provide an implementation, and then a inherited class can completely override that method.&nbsp; That is what the Partial Mock is allowing us to do.</p>
<p>So how do I write my tests?&nbsp; If you don't like using Rhino Mocks you do this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    <span class="kwrd">int</span> expected = 7;
    <span class="kwrd">int</span> result = 0;
    MockRepository mock = <span class="kwrd">new</span> MockRepository();
    MyClass c = mock.PartialMock&lt;MyClass&gt;();

    <span class="kwrd">using</span> (mock.Record())
    {
        Expect.Call(c.Bar()).Return(2);
    }
    <span class="kwrd">using</span> (mock.Playback())
    {
        result = c.Foo();
    }

    Assert.AreEqual(expected, result);
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
Obviously, now my test is referencing the Rhino Mocks library.&nbsp; The variable mock is the Mock Repository.&nbsp; Now the big change is that I don't create MyClass directly, but through the Rhino Mocks PartialMock method.</p>
<p>Next, I tell the mock repository to expect a call to <strong>c.Bar</strong>, and when called return <strong>2</strong>.&nbsp; That is what is happening in the using (<strong>mock.Record()</strong>) section of the code.&nbsp; Then, in the <strong>mock.Playback</strong> section, I call <strong>Foo().</strong></p>
<p>One other quick note, if we were to rewrite <strong>Foo</strong> such that it no longer called <strong>Bar</strong> this test will fail.&nbsp; The <strong>Expect.Call</strong> part tell the mock repository that the method <strong>Bar</strong> will be called, and if it isn't there is a problem.&nbsp; There are ways around that as well, but that is a topic for another day.</p>
<p>Where does that leave us now?&nbsp; Aside from the odd "<strong>virtual</strong>" keyword thrown into our production code, this is the code as you would have originally written it, even without TDD.&nbsp; I don't like making API changes just to satisfy testing, but I am very OK with this change.</p>
<p>&nbsp;</p>
<p>But what about that new kid on the block?&nbsp; You know, <a href="http://code.google.com/p/moq/">Moq</a>.</p>
<p>I still love Rhino Mocks, but I can't help but want to play with a new toy.&nbsp; So here is the same thing, but in Moq:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_moq_test()
{
    Mock&lt;MyClass&gt; mock = <span class="kwrd">new</span> Mock&lt;MyClass&gt;();
    mock.Expect(x =&gt; x.Bar()).Returns(2);

    MyClass c = mock.Object;
    <span class="kwrd">int</span> result = c.Foo();
    Assert.AreEqual(7, result);
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>

<p>So as you should be able to see, Moq is a very different animal than RhinoMocks.&nbsp; There is no Record or Playback (the web site calls those confusing, I disagree, but still), and the <strong>Expect</strong> happens with a anonymous delegate (in the form of the Lambda Expression "<strong>x =&gt; x.Bar()</strong>" where x is of type <strong>MyClass</strong>).</p>
<p>The cool part is that you can get the same results with less code using Moq.&nbsp; That has been the main advantage all along.&nbsp; My informal testing also reveals that Moq is just a hair faster than Rhino Mocks (but not fast enough to warrant switching frameworks).</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/08/partial-mocks-explained/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Mock Objects</title>
	<atom:link href="http://elegantcode.com/tag/mock-objects/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Partial Mocks explained</title>
		<link>http://elegantcode.com/2008/04/08/partial-mocks-explained/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=partial-mocks-explained</link>
		<comments>http://elegantcode.com/2008/04/08/partial-mocks-explained/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:14:42 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/08/partial-mocks-explained/</guid>
		<description><![CDATA[If you are wondering what is prompting this post, it is the fact that on my last post I got schooled by Jeff Brown of Bits-in-Motion.&#160;&#160; Jeff is also one of the minds behind Gallio and MBUnit.&#160; You can only hope to be told you are completely wrong by such a guy. He was very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are wondering what is prompting this post, it is the fact that on my <a href="http://elegantcode.com/2008/04/07/mocking-nested-methods/">last post</a> I got schooled by Jeff Brown of <a href="http://blog.bits-in-motion.com/">Bits-in-Motion</a>.&nbsp;&nbsp; Jeff is also one of the minds behind <a href="http://www.gallio.org">Gallio</a> and <a href="http://www.mbunit.com/">MBUnit</a>.&nbsp; You can only hope to be told you are completely wrong by such a guy. He was very nice about it actually, just stating a preference for a different way of handling the same problem.&nbsp; My problem was that his solution was better than mine.&nbsp; Much better.</p> <p>Where it led me was to re-investigate <a href="http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx">Partial Mocks in Rhino Mocks</a>.&nbsp; My original misunderstanding of Partial Mocks was that they would only mock Abstract Classes.&nbsp; A partial mock will mock ANY class -- but only the Partial mock will only mock abstract methods.&nbsp; That small misunderstanding has caused me to loose untold amount of hair and good will towards all men.</p> <p>So I'm going to re-implement my class methods.&nbsp; Here you go:</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyClass
{
    <span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
    {
        <span class="rem">// stuff happens here</span>
        <span class="kwrd">int</span> i = Bar();
        <span class="rem">// do more stuff here    </span>
        <span class="kwrd">return</span> i + 5;
    }
    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">int</span> Bar()
    {
       <span class="rem">// do some logic</span>
       <span class="kwrd">return</span> 1;
    }
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
A few changes here.&nbsp; First, I removed the delegate and renamed BarInternal back to <strong>Bar</strong>.&nbsp; Second, I marked the <strong>Bar</strong> method as <a href="http://msdn2.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx">virtual</a>.&nbsp; </p>
<p>They key point about a virtual method is that you can provide an implementation, and then a inherited class can completely override that method.&nbsp; That is what the Partial Mock is allowing us to do.</p>
<p>So how do I write my tests?&nbsp; If you don't like using Rhino Mocks you do this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    <span class="kwrd">int</span> expected = 7;
    <span class="kwrd">int</span> result = 0;
    MockRepository mock = <span class="kwrd">new</span> MockRepository();
    MyClass c = mock.PartialMock&lt;MyClass&gt;();

    <span class="kwrd">using</span> (mock.Record())
    {
        Expect.Call(c.Bar()).Return(2);
    }
    <span class="kwrd">using</span> (mock.Playback())
    {
        result = c.Foo();
    }

    Assert.AreEqual(expected, result);
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
Obviously, now my test is referencing the Rhino Mocks library.&nbsp; The variable mock is the Mock Repository.&nbsp; Now the big change is that I don't create MyClass directly, but through the Rhino Mocks PartialMock method.</p>
<p>Next, I tell the mock repository to expect a call to <strong>c.Bar</strong>, and when called return <strong>2</strong>.&nbsp; That is what is happening in the using (<strong>mock.Record()</strong>) section of the code.&nbsp; Then, in the <strong>mock.Playback</strong> section, I call <strong>Foo().</strong></p>
<p>One other quick note, if we were to rewrite <strong>Foo</strong> such that it no longer called <strong>Bar</strong> this test will fail.&nbsp; The <strong>Expect.Call</strong> part tell the mock repository that the method <strong>Bar</strong> will be called, and if it isn't there is a problem.&nbsp; There are ways around that as well, but that is a topic for another day.</p>
<p>Where does that leave us now?&nbsp; Aside from the odd "<strong>virtual</strong>" keyword thrown into our production code, this is the code as you would have originally written it, even without TDD.&nbsp; I don't like making API changes just to satisfy testing, but I am very OK with this change.</p>
<p>&nbsp;</p>
<p>But what about that new kid on the block?&nbsp; You know, <a href="http://code.google.com/p/moq/">Moq</a>.</p>
<p>I still love Rhino Mocks, but I can't help but want to play with a new toy.&nbsp; So here is the same thing, but in Moq:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_moq_test()
{
    Mock&lt;MyClass&gt; mock = <span class="kwrd">new</span> Mock&lt;MyClass&gt;();
    mock.Expect(x =&gt; x.Bar()).Returns(2);

    MyClass c = mock.Object;
    <span class="kwrd">int</span> result = c.Foo();
    Assert.AreEqual(7, result);
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>

<p>So as you should be able to see, Moq is a very different animal than RhinoMocks.&nbsp; There is no Record or Playback (the web site calls those confusing, I disagree, but still), and the <strong>Expect</strong> happens with a anonymous delegate (in the form of the Lambda Expression "<strong>x =&gt; x.Bar()</strong>" where x is of type <strong>MyClass</strong>).</p>
<p>The cool part is that you can get the same results with less code using Moq.&nbsp; That has been the main advantage all along.&nbsp; My informal testing also reveals that Moq is just a hair faster than Rhino Mocks (but not fast enough to warrant switching frameworks).</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/08/partial-mocks-explained/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Mocking nested methods</title>
		<link>http://elegantcode.com/2008/04/07/mocking-nested-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mocking-nested-methods</link>
		<comments>http://elegantcode.com/2008/04/07/mocking-nested-methods/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 02:16:09 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing/QA]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/07/mocking-nested-methods/</guid>
		<description><![CDATA[I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&#160; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&#160; Which probably means it is a bad idea.&#160; After all, if the Internet, [...]]]></description>
			<content:encoded><![CDATA[  <p>I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&nbsp; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&nbsp; Which probably means it is a bad idea.&nbsp; After all, if the Internet, the keeper of all that is right and true, doesn't know about something it must be wrong.</p> <h2>The problem</h2> <p>You have two methods (Foo and Bar), and Foo calls method Bar.&nbsp; It will look like this:</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here<br></span>&nbsp;&nbsp;&nbsp; return i + 5<br>}

<span class="kwrd">public</span> <span class="kwrd">int</span> Bar()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>Now you need to test both methods.&nbsp; Bar can be easily tested like this (this should work for NUnit and MBUnit tests -- assuming both methods exist in a class call MyClass):</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Bar_Test()
{
    MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Bar();
   Assert.AreEqual(1, result);
}</pre>
<p>Now we test Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_Test()
{
   MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Foo();
   Assert.AreEqual(6, result);
}</pre>
<p>Here is where we have an issue.&nbsp; What if the result of Bar changes?&nbsp; That will break the test.&nbsp; So now we have a brittle test.&nbsp; Any time Bar changes, we have to change all of the Bar tests, but also the Foo tests, so we have added complexity to our tests as well.&nbsp; Now if Foo (or Bar) was in a separate class, this wouldn't be an issue, but they are in the same class.&nbsp; And as much as I like small classes, this seems too trivial to split up (even in the context of an extremely trivial example). </p>
<h2>The Solution</h2>
<p>What I would like to do is Mock the method Bar.&nbsp; You can do that with a delegate.</p>
<p>Without really getting into what a delegate is, I will just show the code.&nbsp; So here are my two methods, with a delegate added in for good measure.</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">int</span> BarDelegate();

<span class="kwrd">public</span> BarDelegate Bar;

<span class="kwrd">public</span> MyClass()
{
    Bar = BarInternal;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here    </span>
    <span class="kwrd">return</span> i + 5;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> BarInternal()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>OK, here is what I did:</p>
<ol>
<li>Renamed Bar to BarInternal 
<li>BarDelegate delegate 
<li>Created a variable named Bar to point to the method BarInternal 
<li>Created a constructor to hook up Bar to BarInternal.</li></ol>
<p>Now all of my code can still use the method Bar just like it was there, but in actuality it is calling BarInternal.&nbsp; I have now created one layer of indirection to my method Bar so it can now be mocked and tested.</p>
<p>Here is my new test for Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = BarMethodForTest;
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}

<span class="kwrd">private</span> <span class="kwrd">int</span> BarMethodForTest()
{
    <span class="kwrd">return</span> 2;
}</pre>
<p>So what is new with the test is the BarMethodForTest that is passed to c.Bar and I have coded BarMethodForTest to always return 2.&nbsp; When I set c.Bar to my new method, BarInternal (the default method) is no longer called.</p>
<p>Actually, if I wanted to I could simplify this further by setting c.Bar with an anonymous delegate like this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = <span class="kwrd">delegate</span>() { <span class="kwrd">return</span> 2; }
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}</pre>
<h2>Stepping Back</h2>
<p>OK, take a step back and look at this again with a critical eye.&nbsp; Have I really solved the problem?&nbsp;&nbsp; Yes and no.&nbsp; The real problem was that my methods were too complex to simply test.&nbsp; Now my methods are simple to test, but the code is complex to read.&nbsp; All I've done is shifted the complexity from one class to the other.&nbsp; A better solution would to have created another class and further abstracted out the logic.</p>
<p>At the same time, my class is not overly burdened by the change either.&nbsp; In lieu of a real refactoring, I do consider this a viable solution to the problem.&nbsp; So by all means do this -- but make sure you are out of alternatives first.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/07/mocking-nested-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rhino Mocks presentation &#8211; version 3.3</title>
		<link>http://elegantcode.com/2008/04/07/mocking-nested-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mocking-nested-methods</link>
		<comments>http://elegantcode.com/2008/04/07/mocking-nested-methods/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 02:16:09 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing/QA]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/07/mocking-nested-methods/</guid>
		<description><![CDATA[I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&#160; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&#160; Which probably means it is a bad idea.&#160; After all, if the Internet, [...]]]></description>
			<content:encoded><![CDATA[  <p>I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&nbsp; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&nbsp; Which probably means it is a bad idea.&nbsp; After all, if the Internet, the keeper of all that is right and true, doesn't know about something it must be wrong.</p> <h2>The problem</h2> <p>You have two methods (Foo and Bar), and Foo calls method Bar.&nbsp; It will look like this:</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here<br></span>&nbsp;&nbsp;&nbsp; return i + 5<br>}

<span class="kwrd">public</span> <span class="kwrd">int</span> Bar()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>Now you need to test both methods.&nbsp; Bar can be easily tested like this (this should work for NUnit and MBUnit tests -- assuming both methods exist in a class call MyClass):</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Bar_Test()
{
    MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Bar();
   Assert.AreEqual(1, result);
}</pre>
<p>Now we test Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_Test()
{
   MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Foo();
   Assert.AreEqual(6, result);
}</pre>
<p>Here is where we have an issue.&nbsp; What if the result of Bar changes?&nbsp; That will break the test.&nbsp; So now we have a brittle test.&nbsp; Any time Bar changes, we have to change all of the Bar tests, but also the Foo tests, so we have added complexity to our tests as well.&nbsp; Now if Foo (or Bar) was in a separate class, this wouldn't be an issue, but they are in the same class.&nbsp; And as much as I like small classes, this seems too trivial to split up (even in the context of an extremely trivial example). </p>
<h2>The Solution</h2>
<p>What I would like to do is Mock the method Bar.&nbsp; You can do that with a delegate.</p>
<p>Without really getting into what a delegate is, I will just show the code.&nbsp; So here are my two methods, with a delegate added in for good measure.</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">int</span> BarDelegate();

<span class="kwrd">public</span> BarDelegate Bar;

<span class="kwrd">public</span> MyClass()
{
    Bar = BarInternal;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here    </span>
    <span class="kwrd">return</span> i + 5;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> BarInternal()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>OK, here is what I did:</p>
<ol>
<li>Renamed Bar to BarInternal 
<li>BarDelegate delegate 
<li>Created a variable named Bar to point to the method BarInternal 
<li>Created a constructor to hook up Bar to BarInternal.</li></ol>
<p>Now all of my code can still use the method Bar just like it was there, but in actuality it is calling BarInternal.&nbsp; I have now created one layer of indirection to my method Bar so it can now be mocked and tested.</p>
<p>Here is my new test for Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = BarMethodForTest;
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}

<span class="kwrd">private</span> <span class="kwrd">int</span> BarMethodForTest()
{
    <span class="kwrd">return</span> 2;
}</pre>
<p>So what is new with the test is the BarMethodForTest that is passed to c.Bar and I have coded BarMethodForTest to always return 2.&nbsp; When I set c.Bar to my new method, BarInternal (the default method) is no longer called.</p>
<p>Actually, if I wanted to I could simplify this further by setting c.Bar with an anonymous delegate like this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = <span class="kwrd">delegate</span>() { <span class="kwrd">return</span> 2; }
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}</pre>
<h2>Stepping Back</h2>
<p>OK, take a step back and look at this again with a critical eye.&nbsp; Have I really solved the problem?&nbsp;&nbsp; Yes and no.&nbsp; The real problem was that my methods were too complex to simply test.&nbsp; Now my methods are simple to test, but the code is complex to read.&nbsp; All I've done is shifted the complexity from one class to the other.&nbsp; A better solution would to have created another class and further abstracted out the logic.</p>
<p>At the same time, my class is not overly burdened by the change either.&nbsp; In lieu of a real refactoring, I do consider this a viable solution to the problem.&nbsp; So by all means do this -- but make sure you are out of alternatives first.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/07/mocking-nested-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Mock Objects</title>
	<atom:link href="http://elegantcode.com/tag/mock-objects/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Partial Mocks explained</title>
		<link>http://elegantcode.com/2008/04/08/partial-mocks-explained/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=partial-mocks-explained</link>
		<comments>http://elegantcode.com/2008/04/08/partial-mocks-explained/#comments</comments>
		<pubDate>Wed, 09 Apr 2008 03:14:42 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/08/partial-mocks-explained/</guid>
		<description><![CDATA[If you are wondering what is prompting this post, it is the fact that on my last post I got schooled by Jeff Brown of Bits-in-Motion.&#160;&#160; Jeff is also one of the minds behind Gallio and MBUnit.&#160; You can only hope to be told you are completely wrong by such a guy. He was very [...]]]></description>
			<content:encoded><![CDATA[<p>If you are wondering what is prompting this post, it is the fact that on my <a href="http://elegantcode.com/2008/04/07/mocking-nested-methods/">last post</a> I got schooled by Jeff Brown of <a href="http://blog.bits-in-motion.com/">Bits-in-Motion</a>.&nbsp;&nbsp; Jeff is also one of the minds behind <a href="http://www.gallio.org">Gallio</a> and <a href="http://www.mbunit.com/">MBUnit</a>.&nbsp; You can only hope to be told you are completely wrong by such a guy. He was very nice about it actually, just stating a preference for a different way of handling the same problem.&nbsp; My problem was that his solution was better than mine.&nbsp; Much better.</p> <p>Where it led me was to re-investigate <a href="http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx">Partial Mocks in Rhino Mocks</a>.&nbsp; My original misunderstanding of Partial Mocks was that they would only mock Abstract Classes.&nbsp; A partial mock will mock ANY class -- but only the Partial mock will only mock abstract methods.&nbsp; That small misunderstanding has caused me to loose untold amount of hair and good will towards all men.</p> <p>So I'm going to re-implement my class methods.&nbsp; Here you go:</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MyClass
{
    <span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
    {
        <span class="rem">// stuff happens here</span>
        <span class="kwrd">int</span> i = Bar();
        <span class="rem">// do more stuff here    </span>
        <span class="kwrd">return</span> i + 5;
    }
    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">int</span> Bar()
    {
       <span class="rem">// do some logic</span>
       <span class="kwrd">return</span> 1;
    }
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
A few changes here.&nbsp; First, I removed the delegate and renamed BarInternal back to <strong>Bar</strong>.&nbsp; Second, I marked the <strong>Bar</strong> method as <a href="http://msdn2.microsoft.com/en-us/library/9fkccyh4(VS.80).aspx">virtual</a>.&nbsp; </p>
<p>They key point about a virtual method is that you can provide an implementation, and then a inherited class can completely override that method.&nbsp; That is what the Partial Mock is allowing us to do.</p>
<p>So how do I write my tests?&nbsp; If you don't like using Rhino Mocks you do this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    <span class="kwrd">int</span> expected = 7;
    <span class="kwrd">int</span> result = 0;
    MockRepository mock = <span class="kwrd">new</span> MockRepository();
    MyClass c = mock.PartialMock&lt;MyClass&gt;();

    <span class="kwrd">using</span> (mock.Record())
    {
        Expect.Call(c.Bar()).Return(2);
    }
    <span class="kwrd">using</span> (mock.Playback())
    {
        result = c.Foo();
    }

    Assert.AreEqual(expected, result);
}</pre>
<p>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
Obviously, now my test is referencing the Rhino Mocks library.&nbsp; The variable mock is the Mock Repository.&nbsp; Now the big change is that I don't create MyClass directly, but through the Rhino Mocks PartialMock method.</p>
<p>Next, I tell the mock repository to expect a call to <strong>c.Bar</strong>, and when called return <strong>2</strong>.&nbsp; That is what is happening in the using (<strong>mock.Record()</strong>) section of the code.&nbsp; Then, in the <strong>mock.Playback</strong> section, I call <strong>Foo().</strong></p>
<p>One other quick note, if we were to rewrite <strong>Foo</strong> such that it no longer called <strong>Bar</strong> this test will fail.&nbsp; The <strong>Expect.Call</strong> part tell the mock repository that the method <strong>Bar</strong> will be called, and if it isn't there is a problem.&nbsp; There are ways around that as well, but that is a topic for another day.</p>
<p>Where does that leave us now?&nbsp; Aside from the odd "<strong>virtual</strong>" keyword thrown into our production code, this is the code as you would have originally written it, even without TDD.&nbsp; I don't like making API changes just to satisfy testing, but I am very OK with this change.</p>
<p>&nbsp;</p>
<p>But what about that new kid on the block?&nbsp; You know, <a href="http://code.google.com/p/moq/">Moq</a>.</p>
<p>I still love Rhino Mocks, but I can't help but want to play with a new toy.&nbsp; So here is the same thing, but in Moq:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_moq_test()
{
    Mock&lt;MyClass&gt; mock = <span class="kwrd">new</span> Mock&lt;MyClass&gt;();
    mock.Expect(x =&gt; x.Bar()).Returns(2);

    MyClass c = mock.Object;
    <span class="kwrd">int</span> result = c.Foo();
    Assert.AreEqual(7, result);
}</pre>
<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>

<p>So as you should be able to see, Moq is a very different animal than RhinoMocks.&nbsp; There is no Record or Playback (the web site calls those confusing, I disagree, but still), and the <strong>Expect</strong> happens with a anonymous delegate (in the form of the Lambda Expression "<strong>x =&gt; x.Bar()</strong>" where x is of type <strong>MyClass</strong>).</p>
<p>The cool part is that you can get the same results with less code using Moq.&nbsp; That has been the main advantage all along.&nbsp; My informal testing also reveals that Moq is just a hair faster than Rhino Mocks (but not fast enough to warrant switching frameworks).</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/08/partial-mocks-explained/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Mocking nested methods</title>
		<link>http://elegantcode.com/2008/04/07/mocking-nested-methods/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mocking-nested-methods</link>
		<comments>http://elegantcode.com/2008/04/07/mocking-nested-methods/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 02:16:09 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing/QA]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/04/07/mocking-nested-methods/</guid>
		<description><![CDATA[I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&#160; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&#160; Which probably means it is a bad idea.&#160; After all, if the Internet, [...]]]></description>
			<content:encoded><![CDATA[  <p>I am writing this as a way to document something that is possible, but you probably shouldn't do unless you really need to.&nbsp; Also, I'm sure this is not new, I just can't find any mention of it on Google right now.&nbsp; Which probably means it is a bad idea.&nbsp; After all, if the Internet, the keeper of all that is right and true, doesn't know about something it must be wrong.</p> <h2>The problem</h2> <p>You have two methods (Foo and Bar), and Foo calls method Bar.&nbsp; It will look like this:</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style> <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here<br></span>&nbsp;&nbsp;&nbsp; return i + 5<br>}

<span class="kwrd">public</span> <span class="kwrd">int</span> Bar()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>Now you need to test both methods.&nbsp; Bar can be easily tested like this (this should work for NUnit and MBUnit tests -- assuming both methods exist in a class call MyClass):</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Bar_Test()
{
    MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Bar();
   Assert.AreEqual(1, result);
}</pre>
<p>Now we test Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Foo_Test()
{
   MyClass c = <span class="kwrd">new</span> MyClass();
   <span class="kwrd">int</span> result = c.Foo();
   Assert.AreEqual(6, result);
}</pre>
<p>Here is where we have an issue.&nbsp; What if the result of Bar changes?&nbsp; That will break the test.&nbsp; So now we have a brittle test.&nbsp; Any time Bar changes, we have to change all of the Bar tests, but also the Foo tests, so we have added complexity to our tests as well.&nbsp; Now if Foo (or Bar) was in a separate class, this wouldn't be an issue, but they are in the same class.&nbsp; And as much as I like small classes, this seems too trivial to split up (even in the context of an extremely trivial example). </p>
<h2>The Solution</h2>
<p>What I would like to do is Mock the method Bar.&nbsp; You can do that with a delegate.</p>
<p>Without really getting into what a delegate is, I will just show the code.&nbsp; So here are my two methods, with a delegate added in for good measure.</p><pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">int</span> BarDelegate();

<span class="kwrd">public</span> BarDelegate Bar;

<span class="kwrd">public</span> MyClass()
{
    Bar = BarInternal;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> Foo()
{
    <span class="rem">// stuff happens here</span>
    <span class="kwrd">int</span> i = Bar();
    <span class="rem">// do more stuff here    </span>
    <span class="kwrd">return</span> i + 5;
}

<span class="kwrd">public</span> <span class="kwrd">int</span> BarInternal()
{
   <span class="rem">// do some logic</span>
   <span class="kwrd">return</span> 1;
}</pre>
<p>OK, here is what I did:</p>
<ol>
<li>Renamed Bar to BarInternal 
<li>BarDelegate delegate 
<li>Created a variable named Bar to point to the method BarInternal 
<li>Created a constructor to hook up Bar to BarInternal.</li></ol>
<p>Now all of my code can still use the method Bar just like it was there, but in actuality it is calling BarInternal.&nbsp; I have now created one layer of indirection to my method Bar so it can now be mocked and tested.</p>
<p>Here is my new test for Foo:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = BarMethodForTest;
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}

<span class="kwrd">private</span> <span class="kwrd">int</span> BarMethodForTest()
{
    <span class="kwrd">return</span> 2;
}</pre>
<p>So what is new with the test is the BarMethodForTest that is passed to c.Bar and I have coded BarMethodForTest to always return 2.&nbsp; When I set c.Bar to my new method, BarInternal (the default method) is no longer called.</p>
<p>Actually, if I wanted to I could simplify this further by setting c.Bar with an anonymous delegate like this:</p><pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> FooTest()
{
    MyClass c = <span class="kwrd">new</span> MyClass()
    c.Bar = <span class="kwrd">delegate</span>() { <span class="kwrd">return</span> 2; }
    <span class="kwrd">int</span> result = target.Foo();
    Assert.AreEqual(7, result);
}</pre>
<h2>Stepping Back</h2>
<p>OK, take a step back and look at this again with a critical eye.&nbsp; Have I really solved the problem?&nbsp;&nbsp; Yes and no.&nbsp; The real problem was that my methods were too complex to simply test.&nbsp; Now my methods are simple to test, but the code is complex to read.&nbsp; All I've done is shifted the complexity from one class to the other.&nbsp; A better solution would to have created another class and further abstracted out the logic.</p>
<p>At the same time, my class is not overly burdened by the change either.&nbsp; In lieu of a real refactoring, I do consider this a viable solution to the problem.&nbsp; So by all means do this -- but make sure you are out of alternatives first.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/04/07/mocking-nested-methods/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rhino Mocks presentation &#8211; version 3.3</title>
		<link>http://elegantcode.com/2008/01/28/rhino-mocks-presentation-version-33/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rhino-mocks-presentation-version-33</link>
		<comments>http://elegantcode.com/2008/01/28/rhino-mocks-presentation-version-33/#comments</comments>
		<pubDate>Tue, 29 Jan 2008 04:17:50 +0000</pubDate>
		<dc:creator>Chris Brandsma</dc:creator>
				<category><![CDATA[Mock Objects]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing/QA]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/01/28/rhino-mocks-presentation-version-33/</guid>
		<description><![CDATA[There has been some interest (two people) in updating my Rhino Mocks presentation and re-publishing it. This is from a presentation that I gave for the West Michigan Day of .Net back in May 2007 (ages ago). This presentation consists of a Power Point deck with minimal slides (it was for a code camp) and [...]]]></description>
			<content:encoded><![CDATA[<p>There has been some interest (two people) in updating my Rhino Mocks presentation and re-publishing it. This is from a presentation that I gave for the West Michigan Day of .Net back in May 2007 (ages ago).</p> <p>This presentation consists of a Power Point deck with minimal slides (it was for a code camp) and a sample project written MVP style (WinForms - not web forms).&nbsp; That is where the meat of the presentation was, the slide deck is just there to give a taste of what mock objects are supposed to do.</p> <p>Anyway, the big change was that I updated the sample projects mocking code to Rhino Mocks 3.3 syntax.&nbsp; This uses the Record and Playback methods now.&nbsp; But I did leave one test method using the old syntax for comparison sake.</p> <p>For all of the tests to run you will have to download and install the <a href="http://www.codeplex.com/MSFTDBProdSamples">Adventure Works LT database from CodePlex</a>.</p> <p><a href="http://www.chrisbrandsma.com/RhinoMockDemo.zip">Download the presentation here.</a></p> <p>Enjoy.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/01/28/rhino-mocks-presentation-version-33/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

