<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>mock-objects &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://wordpress.com/tag/mock-objects/</link>
	<description>Feed of posts on WordPress.com tagged "mock-objects"</description>
	<pubDate>Sat, 26 Jul 2008 12:38:44 +0000</pubDate>

	<generator>http://wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[should I worry about the unexpected?]]></title>
<link>http://szczepiq.wordpress.com/?p=92</link>
<pubDate>Sat, 12 Jul 2008 14:35:56 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=92</guid>
<description><![CDATA[The level of validation in typical state testing with assertions is different from typical interacti]]></description>
<content:encoded><![CDATA[<p>The level of validation in typical state testing with assertions is different from typical interaction testing with mocks. Allow me to have a closer look at this subtle difference. My conclusion dares to question the important part of mocking philosophy: <strong>worrying about the unexpected</strong>.</p>
<p>Let me explain by starting from the beginning: a typical interaction based test with mocks (using some pseudo-mocking syntax):</p>
<h3>#1</h3>
<p><img class="size-full wp-image-94" src="http://szczepiq.wordpress.com/files/2008/07/typical-interaction-based-test2.png" alt="Typical interaction based test" width="235" height="402" /></p>
<p><strong>Here is what the test tells me:</strong></p>
<p><strong>- </strong>When you read the article<br />
<strong>- </strong>then the reader.read() should be called<br />
<strong>- </strong>and NO other method on the reader should be called.</p>
<p>Now, let's have a look at typical state based test with assertions:</p>
<h3>#2</h3>
<p><img class="size-full wp-image-95" src="http://szczepiq.wordpress.com/files/2008/07/typical-state-based-test.png" alt="Typical state based test" width="319" height="255" /></p>
<p><strong>Which means:</strong></p>
<p>- When you read the article<br />
- then the article should be read.</p>
<p>Have you noticed the subtle difference between <strong>#1</strong> and <strong>#2</strong>?</p>
<p><strong>In state testing</strong>, an assertion is focused on a single property and doesn't validate the surrounding state. When the behavior under test changes some additional, unexpected property - it will not be detected by the test.</p>
<p><strong>In interaction testing</strong>, a mock object validates all interactions. When the behavior under test calls some additional, unexpected method on a mock - it will be detected and <strong>UnexpectedInteractionError</strong> is thrown.</p>
<p><strong>I wonder if interaction testing should be extra defensive and worry about the unexpected?</strong></p>
<p>Many of you say<strong> 'yes' </strong>but then how come you don't do state based testing along this pattern? I'll show you how:</p>
<h3>#3</h3>
<p><img class="size-full wp-image-96" src="http://szczepiq.wordpress.com/files/2008/07/state-based-test-with-detecting-unexpected.png" alt="State based test can detect the unexpected!" width="333" height="256" /></p>
<p><strong>Which means:</strong></p>
<p>- When you read the article<br />
- then the article should be read<br />
- and no other state on the article should change.</p>
<p>Note that the assertion is made on the entire Article object. It effectively detects any unexpected state changes (e.g: if read() method changes some extra property on the article then the test fails). This way a typical state based test becomes extra defensive just like typical test with mocks.</p>
<p><strong>The thing is state based tests are rarely written like that.</strong> So the obvious question is how come finding the unexpected is more important in interaction testing than in state testing?</p>
<p>Here is my theory: The simplest way to implement a state testing was to provide bunch of assertions (and a runner). Hence simple run-&#62;assert. The simplest way to implement interaction testing was to provide pre-programmable mocks that can be "expected", stubbed with necessary return values,  and later strictly verified.  Hence extra defensive expect-&#62;run-&#62;verify. <strong>I guess the implementation details influenced the interface and defined the patterns of state testing and interaction testing.</strong></p>
<p>I guess it's easier to detect the unexpected with interaction testing (because most mocking frameworks just work like that by default) than with state testing (because I have to build up an expected object which is somewhat unnatural, see <strong>#3</strong>).</p>
<p>Now, let's consider <strong>pros &#38; cons</strong>. Surely detecting the unexpected seems to add credibility and quality to the test. Sometimes however, it just gets in the way, especially when doing TDD. To explain it clearer let's get back to the example <strong>#3</strong>: the state based test with detecting the unexpected enabled. Say I'd like to test-drive a new feature:</p>
<h3>#4</h3>
<p><a href="http://szczepiq.wordpress.com/files/2008/07/test-driving-new-feature.png"><img class="size-full wp-image-97" src="http://szczepiq.wordpress.com/files/2008/07/test-driving-new-feature.png" alt="Test-driving new feature" width="335" height="238" /></a></p>
<p>I run the tests to find out that <strong>newly added test method fails.</strong> It's time to implement the feature:</p>
<p><a href="http://szczepiq.files.wordpress.com/2008/07/adding-new-feature.png"><img class="size-full wp-image-98" src="http://szczepiq.wordpress.com/files/2008/07/adding-new-feature.png" alt="Adding new feature" width="190" height="112" /></a></p>
<p>I run the test again and the new test passes now but hold on... the previous test method fails! Note that the existing functionality is clearly not broken.</p>
<p>What happened? The previous test detected the unexpected change on the article - setting the date. How can I fix it?</p>
<p><strong>1. </strong>I can merge both test methods into one which is probably a good idea in this silly example. However,  many times I really want to have small, separate test methods that are focused around behavior. One-assert-per-test people do it all the time.</p>
<p><strong>2. </strong>Finally, I can stop worrying about the unexpected and focus on testing what is really important:</p>
<p><code>public shouldSetReadDateWhenReading() {<br />
&#160;&#160;article.read();<br />
&#160;&#160;assertEquals(today(), article.getReadDate());<br />
}</code></p>
<p><code>public shouldReadArticle() {<br />
&#160;&#160;article.read();<br />
&#160;&#160;assertTrue(article.isRead());<br />
}</code></p>
<p>Ok, I know the example is silly. But it is only to explain why worrying about unexpected may NOT be such a good friend of TDD or small&#38;focused test methods.</p>
<p><strong>Let's get back to mocking.</strong></p>
<p>Most mocking frameworks detect the unexpected by default. When new features are test-driven as new test methods, sometimes existing tests start failing due to unexpected interaction errors. What happens next?</p>
<p><strong>1. </strong>Junior developers copy-paste expectations from one test to another making the test methods overspecified and less maintainable.</p>
<p><strong>2. </strong>Veteran developers modify existing tests and change the expectations to ignore some/all interactions. Most mocking frameworks enables developers to ignore expectations selectively or object-wise. Nevertheless, it is still a bit of a hassle - why should I change existing tests when the existing functionality is clearly not broken? (like in example <strong>#4</strong> - functionality not broken but the test fails). The other thing is that explicitly ignoring interactions is also a bit like overspecification. After all, to ignore something I prefer just not to write ANYTHING. In state based tests if I don't care about something I don't write an assertion for that. It's simple and so natural.</p>
<p>To recap: worrying about the unexpected sometimes leaves me with overspecified tests or less comfortable TDD. Now, do I want to trade it for the quality? I'm talking about the quality introduced by extra defensive test?</p>
<p><strong>The thing is I didn't find a proof that the quality improves when every test worries about the unexpected.</strong> That's why I prefer to write extra defensive tests <strong>only when it's relevant.</strong> That's why I really like state based testing. That's why I prefer <a href="http://monkeyisland.pl/2008/03/21/lets-spy">spying</a> to mocking. Finally, that's why I don't write verifyNoMoreInteractions() in every <a href="http://mockito.org">Mockito </a>test.</p>
<p>What do you think? Have you ever encountered related problems when test-driving with mocks? Do you find the quality improved when interaction testing worries about the unexpected? Or perhaps should state testing start worrying about the unexpected?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Michael Feathers on TDD]]></title>
<link>http://xplayer.wordpress.com/?p=31</link>
<pubDate>Wed, 18 Jun 2008 14:23:05 +0000</pubDate>
<dc:creator>stoner</dc:creator>
<guid>http://xplayer.wordpress.com/?p=31</guid>
<description><![CDATA[Una breve riflessione di Michael Feathers sul TDD, passando per i mock objects per finire sulla nece]]></description>
<content:encoded><![CDATA[<p>Una<a href="http://michaelfeathers.typepad.com/michael_feathers_blog/2008/06/the-flawed-theo.html"> breve riflessione di Michael Feathers sul TDD</a>, passando per i mock objects per finire sulla necessita' di adottare pratiche che "costringano" a ragionare e riflettere sul nostro codice.</p>
<p>Interessante anche l'excursus sulla storia dei mock objects, nati in Connextra</p>
<blockquote><p>The story I heard was that it was all started by John Nolan, the CTO of a startup named Connextra. John Nolan, gave his developers a challenge: write OO code with no getters.  Whenever possible, tell another object to do something rather than ask.  In the process of doing this, they noticed that their code became supple and easy to change.</p></blockquote>
<p>La frase chiave:</p>
<blockquote><p>We need practices which help us achieve continuous discipline and a continuous state of reflection.  Clean Room and TDD are two practices which, despite their radical differences, force us to think with absolute precision about what we are doing.</p></blockquote>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Diving in to Mock Objects]]></title>
<link>http://xidey.wordpress.com/?p=763</link>
<pubDate>Mon, 16 Jun 2008 14:18:03 +0000</pubDate>
<dc:creator>Anthony Stevens</dc:creator>
<guid>http://xidey.wordpress.com/?p=763</guid>
<description><![CDATA[A new consulting gig I just started last week has a team who is interested in diving deep into Mock ]]></description>
<content:encoded><![CDATA[<p>A new consulting gig I just started last week has a team who is interested in diving deep into Mock Objects as a testing philosophy.  As such, I've spent some time reacquainting myself with Mocking after having passed on it several years ago.</p>
<p>My chief complaint, as the doctors say, was that Mocking introduced an unnecessary level of complexity to your testing code.  My secondary complaint was that it broke encapsulation by giving your test code too much insight as to the expected implementation of your classes, what with all the .expect()s and .will()s floating around.  It's like washing the family car with your Dad hovering over your shoulder, telling you the right way to use the sponge.  As long as it's clean at the end, who cares?</p>
<p>In a nutshell, this is the argument over state-based vs. behavioral testing.  In state-based testing, you just want Car.IsClean() to return true.  In behavioral testing, you want Sponge.Wipe() to be called 137 times, and Hose.Spray() to be called 22 times.</p>
<p>Call me a keen proponent of state-based testing.</p>
<p>There are a couple areas where Mocking can get around very real weaknesses in state-based testing; for example, anything to do with nondeterministic behavior.  The authors of this paper, <a href="http://www.jmock.org/oopsla2004.pdf">"Mock Roles, Not Objects"</a>, conveniently use caching as a way to explore Mocking, and it make sense.  It would be hard to test caching to that level of detail without either (a) Mocks or (b) exposing a lot of guts of the implementation just to hang test hooks off of.</p>
<p>What's your experience with Mocking?  Any best practices to relate?</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Unit testing services built on top of a legacy system]]></title>
<link>http://ketiljensen.wordpress.com/?p=13</link>
<pubDate>Thu, 29 May 2008 21:51:50 +0000</pubDate>
<dc:creator>ketiljensen</dc:creator>
<guid>http://ketiljensen.wordpress.com/?p=13</guid>
<description><![CDATA[I wrote this article, unit testing with mock objects, a couple of years ago. The motivation behind i]]></description>
<content:encoded><![CDATA[<p>I wrote this article, <a href="http://ketiljensen.files.wordpress.com/2008/05/unittestingwithmockobjects.pdf">unit testing with mock objects</a>, a couple of years ago. The motivation behind it was to share some of my experiences from using mock objects when testing a service oriented interface built on top of a legacy backend system. Since then I have gained some more experience about this subject. The article is not updated however to reflect this increase in knowledge (time is a limited resource) . I'm publishing the original article and hope that it may be of interest to somebody out there. Even though I would change a great deal if I was to re-write the article, I still feel that using the Adapter pattern is a good aproach when it comes to testing business logic accessing a legacy backend system.<!--more--></p>
<p>Reading Martin Fowler's article <a href="http://martinfowler.com/articles/mocksArentStubs.html" target="_blank">Mocks Aren't Stubs</a> l came to realize that at the time of writing the article I was very much a mockist. I'm probably still a mockist, in my opinion mock objects is an excellent technical aid when doing TDD and I always felt that using mock objects improve my design. But having used mock objects for a while now, I can see some very clear disadvantages. Amongst other the amount of setup code needed may lead to a maintenance burden if you are not careful. If you start to experience refactoring as a painful exercise, than you probably have a problem. If refactoring is hard you will not favour change. And if you cannot change your code you end up with crap that is hard to maintain...  I've seen this happen and I'm trying my best to avoid this pain in the future. One way of avoiding this is to start treating your test classes as first class citizens and realize that whenever you write code you have increased the maintainance burden for the system.</p>
<p>More to come on this subject, hopefully....</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Test Driven Design using mocks- Lessons Learnt (Part 2)]]></title>
<link>http://isaiahperumalla.wordpress.com/?p=9</link>
<pubDate>Wed, 28 May 2008 22:19:56 +0000</pubDate>
<dc:creator>isaiahperumalla</dc:creator>
<guid>http://isaiahperumalla.wordpress.com/?p=9</guid>
<description><![CDATA[This is a follow up to my previous post. In this somewhat contrived example we are building a point ]]></description>
<content:encoded><![CDATA[<p>This is a follow up to my previous <a href="../2008/04/25/test-driven-design-using-mocks-%E2%80%93-lessons-learnt-part-1/" target="_self"><span style="color:blue;">post</span></a>. In this somewhat contrived example we are building a point of sale system and there is a requirement to print out a receipt for a sale, which includes item details, total taxes and the total amount due.<br />
Using Rinho mocks Here is the first test I wrote initially, which drove out the need<br />
for a Renderer role, whose responsibility is to render the contents of the receipt<br />
onto an output device</p>
<p>[TestFixture]<br />
public class SalesTests<br />
{<br />
private MockRepository mockery;</p>
<p>[SetUp]<br />
public void BeforeTest()<br />
{<br />
mockery = new MockRepository();<br />
}</p>
<p>[TearDown]<br />
public void AfterTest()<br />
{<br />
mockery.VerifyAll();<br />
}</p>
<p>[Test]<br />
public void ShouldbeAbleToPrintReceiptForASaleWithNoItems()<br />
{<br />
var sale = new Sale();<br />
var renderer = mockery.StrictMock&#60;IRender&#62;();<br />
renderer.Render(”Total Taxes: 0.00 \n Total: 0.00″);<br />
mockery.ReplayAll();<br />
sale.PrintReceiptOn(renderer);</p>
<p>}<br />
}<br />
the implementation needed to pass the above test was as follows</p>
<p>public interface Renderer{<br />
void render(String s);<br />
}<br />
public class Sale {</p>
<p>public void PrintReceiptOn(IRender renderer)<br />
{<br />
renderer.Render(”Total Taxes: 0.00 \n Total: 0.00″);<br />
}</p>
<p>By driving the design test first I was able to discover the need for an object to play the Renderer role, using mocks I was able to drive out interface for the Renderer role.<br />
But I also realised later the above test was brittle and over specified, because<br />
the test was very tightly coupled to the implementation, because the conversation between the objects was not at the right level.<br />
for instance if I changed the implementation of printReceiptOn on the Sale object to</p>
<p>public void PrintReceiptOn(IRender renderer)<br />
{</p>
<p>renderer.Render(”Total Taxes: 0.00″);<br />
renderer.Render(”Total: “);<br />
renderer.Render(”0.00″);<br />
}</p>
<p>The test will break (because the test specifies the Render message be sent to the renderer only once with a specific argument) although the implementation is<br />
quite valid. So the test is tightly coupled to the implementation<br />
Now we could try addressing the symptom by defining a looser constraint on the test as shown below</p>
<p>[Test]<br />
public void ShouldbeAbleToPrintReceiptForASaleWithNoItems()<br />
{<br />
var sale = new Sale();<br />
var renderer = mockery.StrictMock&#60;IRender&#62;();<br />
renderer.Render(”Total: 0.00″);<br />
LastCall.Repeat.AtLeastOnce().IgnoreArguments();<br />
mockery.ReplayAll();<br />
sale.PrintReceiptOn(renderer);</p>
<p>With the above either of my previous implementation would make the<br />
test pass. however it  doesn’t test the right data was being rendered.</p>
<p>To ensure that the right data was being rendered<br />
We could write a state-based   using a collecting stub to verify the data being<br />
rendered is correct as shown below<br />
[Test]</p>
<p>public void VerifyReceiptContentsForSaleWithNoItems() {<br />
TestRenderer renderingDevice = new TestRenderer();<br />
sale.printReceiptOn(renderingDevice);<br />
Assert.assertEquals(”Total Taxes: 0.00 \n Total: 0.00″,<br />
renderingDevice.GetContents());</p>
<p>}</p>
<p>where TestRenderer is a collecting stub which is implemented as follows</p>
<p>public class TestRenderer  : IRenderer {<br />
private String contents;</p>
<p>public void Render(String s) {<br />
contents += s;<br />
}<br />
public String GetContents() {<br />
return contents;<br />
}<br />
}<br />
At this point I was questioning the usefulness of a mock, it seemed I was better off using a state based test and using a colleting stub to verify. The brittleness of our initial interaction based test, indicated an underlying design issue,  interaction was not specified at the right level.  The trick here is to design interactions that are meaningful to the calling object, this leads to interface discovery, (and this is one of the reasons <a href="http://www.mockobjects.com/2007/04/test-smell-everything-is-mocked.html">why you should not mock 3rd party API's</a>). Now Render(string s) is not a meaningful message to the Sale object to be sending to the Renderer, the Sale object knows about items, taxes and total so What would have been more a meaningful interaction (conversation ) between the Sale object and Renderer would be to specify the interaction in terms of taxes, items and total, as shown below.</p>
<p>[Test]<br />
public void ShouldbeAbleToPrintReceiptOnAPrinterForSaleWithNoItems()<br />
{<br />
renderer.RenderTaxes(0.0m);<br />
renderer.RenderTotal(0.0m);<br />
mockery.ReplayAll();<br />
saleUnderTest.PrintReceiptOn(printer);<br />
}<br />
public interface Renderer {<br />
void RenderTotal(decimal total);<br />
void RenderTaxes(decimal taxes);<br />
}</p>
<p>the following is now the implementation of the PrintReceiptOn method of the Sale Object</p>
<p>public void PrintReceiptOn(IRender renderer)<br />
{</p>
<p>renderer.RenderTaxes(totalTaxes);<br />
renderer.RenderTotal(total);<br />
}<br />
This is where mock objects are so useful as they aid in the discovery of interfaces and quickly give us feedback in the form of brittle tests when interactions between objects are poorly designed.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mocking Web Services in InfoQ]]></title>
<link>http://upulgodage.wordpress.com/?p=21</link>
<pubDate>Mon, 12 May 2008 14:04:19 +0000</pubDate>
<dc:creator>upulgodage</dc:creator>
<guid>http://upulgodage.wordpress.com/?p=21</guid>
<description><![CDATA[Writing on the recent happenings in the Web services testing approaches, Boris Lublinsky has reviewe]]></description>
<content:encoded><![CDATA[<p>Writing on the recent happenings in the Web services testing approaches, Boris Lublinsky has reviewed my tutorial in an <a title="Mocking Web Services" href="http://www.infoq.com/news/2008/05/WSMock">InfoQ post</a>. You can read my tutorial, <a title="Mock Web services with Apache Synapse to develop and test Web services" href="http://www.ibm.com/developerworks/edu/ws-dw-ws-synapse.html">Mock Web services with Apache Synapse to develop and test Web services</a>, in the IBM developerWorks.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mock Web services with Apache Synapse to develop and test Web services]]></title>
<link>http://upulgodage.wordpress.com/?p=20</link>
<pubDate>Thu, 01 May 2008 16:19:02 +0000</pubDate>
<dc:creator>upulgodage</dc:creator>
<guid>http://upulgodage.wordpress.com/?p=20</guid>
<description><![CDATA[Apache Synapse is a simple, lightweight, high-performance       enterprise service bus (ESB) release]]></description>
<content:encoded><![CDATA[<p><a title="Apache Synapse" href="http://synapse.apache.org">Apache Synapse</a> is a simple, lightweight, high-performance       enterprise service bus (ESB) released under the Apache License, Version 2.0. But for an individual       developer, what's the use of an ESB product in your day-to-day life? The simplicity       of the configuration, out-of-the-box feature set, extensible architecture, and the       minimal footprint makes it a versatile and powerful tool that you can use for a       variety of tasks.</p>
<p>In this <a title="IBM developerWorks" href="http://www.ibm.com/developerworks/">IBM developerWorks</a> tutorial, I will explain how you can use Apache Synapse to create       mock Web services. The target Web service clients and services can be in any language, such as           Microsoft® .NET, Java, or PHP. You will work with several samples, starting           from the most basic configuration and gradually building more complex solutions           to create mock Web services.</p>
<p>Read the article at <a title="Mock Web services with Apache Synapse to develop and test Web services" href="http://www.ibm.com/developerworks/webservices/edu/ws-dw-ws-synapse.html">http://www.ibm.com/developerworks/webservices/edu/ws-dw-ws-synapse.html</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[London Geek Night]]></title>
<link>http://szczepiq.wordpress.com/?p=85</link>
<pubDate>Sun, 27 Apr 2008 18:31:07 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=85</guid>
<description><![CDATA[Thoughtworks office in London holds a Geek Night on 28/05/2008.
It&#8217;s open for everyone so don]]></description>
<content:encoded><![CDATA[<p><a href="http://maps.google.co.uk/maps?f=q&#38;hl=en&#38;q=ThoughtWorks+Ltd.+9th+Floor+Berkshire+House,+168-173+High+Holborn,+London,+WC1V+7AA&#38;layer=&#38;ie=UTF8&#38;z=17&#38;om=1&#38;iwloc=A">Thoughtworks office in London</a> holds a <a href="http://londongeeknights.wetpaint.com/page/Mocking+with+Java+Night">Geek Night</a> on 28/05/2008.</p>
<p>It's open for everyone so don't plan anything for the last Wednesday of May.</p>
<p>The topic concentrates around mocking. There will be jMock guys selling <a href="http://jmock.org">jMock</a> and <a href="http://wuetender-junger-mann.de/wordpress/">Felix</a> talking about <a href="http://mockito.org">Mockito</a>. Trust me, even if you know everything about mocking, this session will be interesting.</p>
<p>I'm not going to be there because in few days I'm moving to a different country :)</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Apache Synapse simulate mediator]]></title>
<link>http://upulgodage.wordpress.com/?p=33</link>
<pubDate>Sun, 27 Apr 2008 03:26:59 +0000</pubDate>
<dc:creator>upulgodage</dc:creator>
<guid>http://upulgodage.wordpress.com/?p=33</guid>
<description><![CDATA[Simulate mediator is a pluggable extension to Apache Synapse and WSO2 ESB, Enterprise Service Bus pr]]></description>
<content:encoded><![CDATA[<p>Simulate mediator is a pluggable extension to Apache Synapse and WSO2 ESB, Enterprise Service Bus products. It performs regular expression matches against the message and if all the matches succeed, it replaces the message with the given contents of the file. You can replace the whole SOAP envelope or replace only the body contents. This mediator can be used to simulate Web service responses for development and testing. Check out the sample, and download the binary with the source code <a title="Simulate mediator" href="http://esbsite.org/resources.jsp?path=/mediators/upul/Simulate%20Mediator">here</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[is there a difference between asking and telling?]]></title>
<link>http://szczepiq.wordpress.com/?p=78</link>
<pubDate>Sat, 26 Apr 2008 16:49:46 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=78</guid>
<description><![CDATA[These days testing interactions is getting very common. Mocking tools are becoming a necessary suppl]]></description>
<content:encoded><![CDATA[<p>These days testing <strong>interactions</strong> is getting very common. Mocking tools are becoming a necessary supplement to xUnit libraries precisely to facilitate testing interactions. I cannot imagine writing software without <em>assert()</em> (to test state) and <em>verify()</em> (to test interactions).</p>
<p>I'm about to show that it is very useful to distinguish two basic kinds of interactions: <strong>asking an object of data</strong> and <strong>telling</strong> <strong>an object to do something</strong>. Fair enough, it may sound obvious but most mocking frameworks treat all interactions equally and don't take advantage of the distinction.</p>
<p>Let's have a look at this piece of code:</p>
<p style="text-align:center;"><img class="aligncenter size-full wp-image-82" src="http://szczepiq.wordpress.com/files/2008/04/asking_and_telling_ss.png" alt="Difference between asking and telling" width="450" height="120" /></p>
<p>Before mocking was invented we manually wrote stubs and tests looked like this:</p>
<p style="text-align:center;"><img class="size-full wp-image-81 aligncenter" src="http://szczepiq.wordpress.com/files/2008/04/old_ways_s.png" alt="Good old hand crafted stubs" width="386" height="130" /></p>
<p>Sometimes I miss those days before mocking. Test code looked so nice... The only problem was that hand writing every stub was quite cumbersome and produced tons of extra code.</p>
<p>Anyway, let's try to extract a pattern from above test code:</p>
<p><strong>1. </strong>when the repository is asked to find "foo" article, then return <em>article</em><strong><br />
2. </strong>deleteByHeadline("foo");<strong><br />
3. </strong>make sure repository was told to delete <em>article</em></p>
<p>So, to generalize it:</p>
<p><strong>1.</strong> stub<strong><br />
2.</strong> run<strong><br />
3.</strong> assert</p>
<p>Now, let's put it into words:</p>
<p>Interaction that is <strong>asking an object for data (or <a href="http://xunitpatterns.com/indirect%20input.html">indirect input</a>)</strong> is basically providing necessary input for processing.  This kind of interaction is meant to be <strong>stubbed before</strong><strong> </strong>running code under test (exercising the behaviour).</p>
<p>Interaction that is <strong>telling an object to do something (or <a href="http://xunitpatterns.com/indirect%20output.html">indirect output</a>)</strong> is basically the outcome of processing.  This kind of interaction is meant to be <strong>asserted after</strong> running code under test.</p>
<p>Testing interactions like that is more natural and produces better code. Lessons learned from the old ways of testing interactions are implemented in <a href="http://mockito.org">Mockito</a>:</p>
<p><img class="aligncenter size-full wp-image-83" src="http://szczepiq.wordpress.com/files/2008/04/mockito_with_asking_and_telling_s.png" alt="Mockito distinguishes asking and telling" width="450" height="122" /></p>
<h2 style="text-align:center;">Controversies</h2>
<p>Above approach <a href="http://codebetter.com/blogs/aaron.jensen/archive/2008/04/03/separate-stub-and-verify-duplicate-code-necessarily.aspx">may seem controversial</a> (quoting interesting para):</p>
<blockquote><p>Then, when you do verify(...), you have to basically repeat the exact same expression you put in stub(...). This might work if you only have a couple calls to verify, but for anything else, <strong>it will be a lot of repeated code</strong>, I'm afraid</p></blockquote>
<p>Basically, the controversy is about repeating the same expression in <em>stub()</em> and <em>verify()</em>:</p>
<p style="text-align:center;"><img class="aligncenter" src="http://szczepiq.files.wordpress.com/2008/04/repeating_verify_s.png" alt="Do I really need to repeate myself?" width="519" height="157" /></p>
<p>Do I really have to repeat the same expression? After all, stubbed interactions <strong>are verified implicitly</strong>. The execution flow of my own code does it completely <strong>for free</strong>. <a href="http://codebetter.com/blogs/aaron.jensen/archive/2008/04/03/separate-stub-and-verify-duplicate-code-necessarily.aspx">Aaron Jensen</a> also noticed that:</p>
<blockquote><p>If you're verifying you don't need to stub unless of course that method returns something that is critical to the flow of your test (or code), in which case you don't really need to verify, because the flow would have verified.</p></blockquote>
<p>Just to recap: <strong>there is no repeated code.</strong></p>
<p>But what if an interesting interaction <strong>shares the characteristic of both asking and telling?</strong> Do I have to repeat interactions in stub() and verify()? Will I end up with duplicated code? Not really. In practice: <strong>If I stub</strong> then it is verified for free, so <strong>I don't verify</strong>. <strong>If I verify</strong> then I don't care about the return value, so <strong>I don't stub</strong>. Either way, <strong><a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">I don't repeat myself</a></strong>. In theory though, I can imagine a rare case where I do verify a stubbed interaction, for example to make sure the stubbed interaction happened exactly <em>n times</em>. But this is a different aspect of behavior and apparently an interesting one. Therefore I want to be explicit and I am perfectly happy to sacrifice one extra line of code...</p>
<h2 style="text-align:center;">Finally...</h2>
<p><strong>Mockito recognises the difference </strong>between asking and telling, hence<strong> stubbing is separated from verification.</strong> Stubbing becomes a part of setup whereas verification a part of assertions. This produces cleaner code and gives more natural testing/<a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a>. It doesn't increase code duplication as one might think. It's just one of the ideas implemented in Mockito to make the <strong>mocking experience a little bit better</strong>. It's not a silver bullet, though. Decent code is easily testable regardless of any mocking tools.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Test Driven Design using mocks – Lessons learnt (Part 1)]]></title>
<link>http://isaiahperumalla.wordpress.com/?p=7</link>
<pubDate>Fri, 25 Apr 2008 12:59:30 +0000</pubDate>
<dc:creator>isaiahperumalla</dc:creator>
<guid>http://isaiahperumalla.wordpress.com/?p=7</guid>
<description><![CDATA[Lesson 1 - “Specify conversations between objects an abstract enough level”
A common complaint w]]></description>
<content:encoded><![CDATA[<p class="MsoNormal"><strong><span>Lesson 1 - <em>“Specify conversations between objects an abstract enough level”</em></span></strong></p>
<p class="MsoNormal"><strong></strong>A common complaint with using mock objects is that interaction based tests ties your tests to the implementation details of the production code and interaction based tests are tracking the implementation of the method you’re testing. I felt this many times previously, every time I refactored my production code some of my tests seem to break even though, functionality of the object remained the same. Often mocks and interaction based testing are blamed for brittle tests. I have come to realize any brittleness exposed by interaction based tests is just a symptom of an over specified test or their is an underlying design issue because of a weak interaction model.</p>
<p>Interaction tests will be brittle and tied to the implementation if you dont specify interactions at the right level, and your tests will quickly let you know. After spending time doing some development in the <a href="http://seaside.st" target="_blank">Smalltalk world</a>, i rediscovered that OO is all about message passing (object interactions). So a good OO model must have a good interaction model, with this in mind i have come to realize that the key to interaction based testing is specifying interactions (or conversations) between an object and its collaborators at the right level. An object should tell its collaborator what it should get done and not how it should do it. This drives us not to include even a hint of implementation detail when designing our interactions between the object under test and it collaborator, this forces us to create collaborator interface at an abstract enough so that no implementation details gets in the way, this leads to what is often called interface discovery of the collaborating objects, and is a great exploratory way to design the interface of collaborators and distribute responsibilities between objects and mocks are a vital tool to do this. This is what <a href="http://mockobjects.com/" target="_blank">Steve Freeman and Nat Pryce</a> have been telling us all along, but its only now I’m starting to understand this. However i also learnt not to use mocks everywhere, generally if I cannot model interactions between an object and its collaborator at an abstract enough level that made sense to the calling objects domain, it generally means i'm unable to define a clear <a href="http://martinfowler.com/bliki/RoleInterface.html">role interface</a> for the collaborating object, then in this case i would not use mocks at all, rather I tend to use a real object or a stub and test a cluster of objects together.<br />
So what do I mean by “Specifying conversations between objects an abstract level”. I will try explaining by giving an example in the <a href="http://isaiahperumalla.wordpress.com/2008/05/28/test-driven-design-using-mocks-lessons-learnt-part-2/">next post</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mock Objects]]></title>
<link>http://hsidev.wordpress.com/2008/04/18/mock-objects-a-gentle-introduction-by-k-scott-allen/</link>
<pubDate>Fri, 18 Apr 2008 16:27:20 +0000</pubDate>
<dc:creator>Nathan</dc:creator>
<guid>http://hsidev.wordpress.com/2008/04/18/mock-objects-a-gentle-introduction-by-k-scott-allen/</guid>
<description><![CDATA[Nice intro to using Mock Objects in .NET - provides some discussion on the two main mock frameworks ]]></description>
<content:encoded><![CDATA[<p>Nice intro to using Mock Objects in .NET - provides some discussion on the two main mock frameworks in addition to an overview and a general idea of why and how to use this useful libraries.</p>
<p><a href="http://odetocode.com/Blogs/scott/archive/2008/04/17/12013.aspx">The article is here</a></p>
<p>Scott has a follow up article on mocks (Mocks - It's a Question of When) discussing when you would choose to use mocking, <a href="http://odetocode.com/Blogs/scott/archive/2008/05/01/12044.aspx">which is here</a></p>
<p>&#160;</p>
<p>Martin Fowler has an article about the art and science of mocking, called "<a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks Aren't Stubs</a>" that is also well worth reading.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mocking Events [With RhinoMocks]]]></title>
<link>http://chakkaradeep.wordpress.com/2008/04/03/mocking-events-with-rhinomocks/</link>
<pubDate>Thu, 03 Apr 2008 10:37:26 +0000</pubDate>
<dc:creator>Chaks</dc:creator>
<guid>http://chakkaradeep.wordpress.com/2008/04/03/mocking-events-with-rhinomocks/</guid>
<description><![CDATA[Suppose we have an Inerface called IFooDatabase . Think this Interface as our gateway which will pro]]></description>
<content:encoded><![CDATA[<p>Suppose we have an Inerface called <i>IFooDatabase</i> . Think this Interface as our gateway which will provide us with basic database operations.</p>
<p>Now, how does Mocking come here?  - My friend is still working on this database layer but he has given me already the Interface with which he is implementing the Database Class, so that I can make use of that and <i>mock,</i> as if that database layer exists and test my program against it.</p>
<p>What mocking framework I am using? - <a href="http://www.ayende.com/projects/rhino-mocks.aspx">RhinoMocks</a></p>
<p>My friend told me that he is going to add events for each database operation, like <i>InsertEvent</i>, <i>UpdateEvent</i>, <i>DeleteEvent</i> so that they may be raised for each <i>insertion</i>, <i>updation</i> and <i>deletion</i> operations respectively.</p>
<p>For this post, to make it simple, let me take just the <i>InsertEvent</i>. Here is the class diagram,</p>
<p><img src="http://chakkaradeep.files.wordpress.com/2008/04/040208-2137-mockingeven1.png" /></p>
<p>And here is my Class which is going to make use of this Interface</p>
<p><img src="http://chakkaradeep.files.wordpress.com/2008/04/040208-2137-mockingeven2.png" /></p>
<p>I was pretty happy that my friend provided me an Interface to mock all the database activities, but I was really stuck on how do I test all those Events are raised!</p>
<p>Well, been using one of the best Mocking Frameworks around, RhinoMocks did provided a way to mock Events ;)</p>
<p>So, here is my test case,</p>
<p><span style="font-family:Courier New;font-size:10pt;">[<span style="color:#2b91af;">Test</span>]<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:blue;">public </span><span style="color:blue;">void</span> TestInsertEventRaised()</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">{<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">MockRepository</span> fooDatabaseMock = <span style="color:blue;">new</span><br />
<span style="color:#2b91af;">MockRepository</span>();<br />
<span style="color:#2b91af;"></span></span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">IFooDatabase</span> </span></p>
<p><span style="font-family:Courier New;font-size:10pt;">   fooDatabase = fooDatabaseMock.DynamicMock&#60;<span style="color:#2b91af;">IFooDatabase</span>&#62;();</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">fooDatabase.FooDatabaseInsertEvent += <span style="color:blue;">null</span>;<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">LastCall</span>.IgnoreArguments();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">IEventRaiser</span><br />
fooEventRaiser = <span style="color:#2b91af;">LastCall</span>.GetEventRaiser();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">    fooDatabaseMock.ReplayAll();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">Foo</span> myFoo = <span style="color:blue;">new</span><br />
<span style="color:#2b91af;">Foo</span>(fooDatabase);<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">    fooEventRaiser.Raise(<span style="color:blue;">this</span>, <span style="color:#2b91af;">EventArgs</span>.Empty);<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">Assert</span>.IsTrue(myFoo.InsertEventRaised);<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">}</span></p>
<p>RhinoMocks provides an interface called IEventRaiser which you can use to raise events!</p>
<p>Here is what we are doing,</p>
<ul>
<li>I am assigning <i>null </i>to the EventHandler and telling RhinoMocks that please do ignore the arguments in my last call. This helps us because we may associate our event to any Event Handler with different event arguments</li>
<li>We initialize IEventRaiser by getting the last event, which in our case is <i>FooDatabaseInsertEvent</i></li>
<li>We pass on the Database object which is mocked to my Foo class to use</li>
<li>And finally we raise that last event</li>
<li>And do a simple Boolean check to see actually we did raise the event</li>
</ul>
<p>Wasn't that easy ;)</p>
<p>You may complain that I have used the generalized EventArgs and completed this post. What about custom EventArgs?</p>
<p>No worries, that also takes the same route ;)</p>
<p><span style="font-family:Courier New;font-size:10pt;">[<span style="color:#2b91af;">Test</span>]</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:blue;">public</span> <span style="color:blue;">void</span> TestUpdateEventRaised()<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">{<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">MockRepository</span> fooDatabaseMock = <span style="color:blue;">new</span><br />
<span style="color:#2b91af;">MockRepository</span>();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">IFooDatabase</span> </span></p>
<p><span style="font-family:Courier New;font-size:10pt;">  fooDatabase = fooDatabaseMock.DynamicMock&#60;<span style="color:#2b91af;">IFooDatabase</span>&#62;();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">    fooDatabase.FooDatabaseUpdateEvent += <span style="color:blue;">null</span>;<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">LastCall</span>.IgnoreArguments();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">IEventRaiser</span> fooEventRaiser = <span style="color:#2b91af;">LastCall</span>.GetEventRaiser();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">    fooDatabaseMock.ReplayAll();<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">Foo</span> myFoo = <span style="color:blue;">new</span><br />
<span style="color:#2b91af;">Foo</span>(fooDatabase);<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">    fooEventRaiser.Raise(<span style="color:blue;">this</span>, <span style="color:blue;">new</span><br />
<span style="color:#2b91af;">FooDatabaseEventArgs</span>(<span style="color:#a31515;">"datbase"</span>,<span style="color:blue;">true</span>));<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;"><span style="color:#2b91af;">Assert</span>.IsTrue(myFoo.UpdateEventRaised);<br />
</span></p>
<p><span style="font-family:Courier New;font-size:10pt;">}</span></p>
<p>The <i>FooDatabaseEventArgs</i> is our custom EventArgs.</p>
<p>I would recommend anyone reading this post to try out the sample posted below if you really want to understand what is happening ;)</p>
<p>You can download the sample <a href="http://cid-8a2653578ab2c83b.skydrive.live.com/self.aspx/Public/MockingEvents.zip">here</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[let's spy]]></title>
<link>http://szczepiq.wordpress.com/?p=76</link>
<pubDate>Fri, 21 Mar 2008 00:11:28 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=76</guid>
<description><![CDATA[Following Gerard Meszaros: &#8220;Good names help us communicate the concepts&#8221;.
There is this ]]></description>
<content:encoded><![CDATA[<p>Following <a href="http://xunitpatterns.com/Whats%20in%20a%20Name.html">Gerard Meszaros</a>: "Good names help us communicate the concepts".</p>
<p>There is this <a href="http://mockito.org">Test Spy framework</a> I worked on lately. Unfortunately, it doesn't use 'test spy' metaphor at all. It talks about 'mocks' all the time. Some even say that the name of the library has something to do with mocking...</p>
<p>Was I just a foolish ignorant who didn't want to acknowledge different kinds of mocks. Ouch! I should say: <a href="http://xunitpatterns.com/Test%20Double.html">Test Doubles</a>. In case you haven't heard about <b>Doubles</b>: all those substitutes of real objects that make testing simpler <b>or</b> faster <b>or</b> more maintainable. I like them because they <b>shrink the unit under test</b> and make it easier to test.</p>
<p>I like simplicity. Introducing new concepts doesn't make things simple. Do I really need <a href="http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html"><b>Double, Dummy, Fake, Mock, Spy </b>and<b> Stub</b></a> to write decent code? On the other hand, I definitely need them to <b>communicate</b> how to write decent code.</p>
<p>At the back of my weird mind I used to think that Test Double breakdown was a bit disconnected from the reality where subtle differences are blurred (and the existing tools/libraries didn't really reduce the confusion). I tried to keep things plain but I reached the boundary: <b>trying to keep things simple</b> (and sticking to <a href="http://martinfowler.com/articles/mocksArentStubs.html">mocks and stubs</a>) actually could have <b>increased the confusion</b> and made things complicated.</p>
<p><img src="http://szczepiq.wordpress.com/files/2008/03/jamesbond.jpeg" alt="JamesBond" align="left" height="167" width="45" />That's why I'm about to sort out Mockito terminology. Better late than never, right?</p>
<p>In all of my previous posts <b>'Mockito mock'</b> should be read <b>'Test Spy'</b>. But what's the Test Spy anyway? Or better: <b>what's the difference between a Test Spy and a Mock?</b> Both serve verifying interactions but the Spy is simple, lightweight and it gives very natural testing experience, close to good old assertions. Sounds interesting? Have a look at some of my previous rants or read <a href="http://hamletdarcy.blogspot.com/2007/10/mocks-and-stubs-arent-spies.html">this excellent post</a> by Hamlet D'Arcy (don't miss <a href="http://www.hamletdarcy.com/files/2007/MocksAreNotSpies.jpg">Collaborator Continuum</a>).</p>
<p>Let's get back to my favourite Test Spy Framework. Do you think following changes makes things simpler and easier to understand (I  don't really know the answer...):</p>
<p><b>@Mock -&#62; @Spy</b></p>
<p><b> mock(Foo.class) -&#62; createSpy(Foo.class)</b></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mockito @ Agile 2008]]></title>
<link>http://szczepiq.wordpress.com/?p=69</link>
<pubDate>Sun, 24 Feb 2008 22:14:21 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=69</guid>
<description><![CDATA[Just submitted session proposal for Agile 2008. It&#8217;s about Mockito (yes, I know I&#8217;m bori]]></description>
<content:encoded><![CDATA[<p>Just submitted <a href="http://submissions.agile2008.org/node/4274">session proposal</a> for Agile 2008. It's about Mockito (yes, I know I'm boring).</p>
<p>Competition is fierce and without proper (read: famous) name it will be difficult to get approved. But anyway: deadline for submissions is tomorrow. If you have any feedback about <a href="http://submissions.agile2008.org/node/4274">my session</a> and you are willing to share it with me before end of tomorrow - I would be grateful.</p>
<p>I'm gonna present short version of this session during coming Last Thursday at Holborn office - see you there!</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Can I test what I want, please?]]></title>
<link>http://szczepiq.wordpress.com/?p=67</link>
<pubDate>Sun, 24 Feb 2008 14:00:52 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=67</guid>
<description><![CDATA[Here&#8217;s the deal:
In state based testing (or return value testing) I assert that certain proper]]></description>
<content:encoded><![CDATA[<p>Here's the deal:</p>
<p><b>In state based testing</b> (or return value testing) I assert that certain property has changed. I don't care if other properties have changed - unless I explicitly write assertions for them. Great benefit of this style is the flexibility of testing: I can write small, targeted test methods. Basically, <b>I can test what I want</b>.</p>
<p><b>In interaction based testing</b> I expect an interaction to happen. Even if I don't care about other interactions I still have to expect them - to satisfy invasive mocks. This is how most mocking frameworks work and as a result, I cannot write small, targeted test methods. Basically, <b>I cannot test what I want</b>.</p>
<p>Some mocking frameworks are not invasive. Others offer tricks to reduce this problem - with various success rate and usually with side effects. Instead of jumping into examples let me ask you:</p>
<p><b>Does your mocking framework let you test what you want? </b></p>
<p>Expecting a single interaction in most mocking frameworks means: <b>1.</b> this interaction <b>must</b> happen. <b>2.</b> other interactions <b>must NOT</b> happen. Do you imagine if an innocent assertion of the state worked like that? Asserting one property meaning also asserting that <b>NONE</b> of the other properties have changed?</p>
<p><img src="http://szczepiq.wordpress.com/files/2008/02/shield.jpeg" alt="defensive" align="left" />Let me rephrase my initial question: <b>Why testing interactions has to be more defensive than testing state?</b></p>
<p>Is it because we fell in love with pre-programmed, intelligent mocks?  Is it because of the way mocking frameworks are implemented? Or perhaps because of the strive to have a decent point of failure - mock can bark with unexpected interaction straight in the code so it's very easy to find it?</p>
<p><b>I'm not buying it.</b> When it comes to behaviour verification, Mockito provides excellent point of failure. Also, Mockito can detect any kind of unexpected interactions. Oh, and Mockito lets me test what I want...</p>
<p><b>Mockito mocks are tamed.</b> They don't make decisions for me. They don't know which interactions are expected or unexpected. I rule my mocks. I rule my code. And it pays back generously: code is cleaner and reacts better to changes.</p>
<p>By now, you've probably figured out that Mockito <b>is not strictly a mocking framework.</b> It's rather a spying/stubbing framework but that's a story for a <a href="http://monkeyisland.pl/2008/03/21/lets-spy">different post</a>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Revisiting Mock Objects]]></title>
<link>http://chakkaradeep.wordpress.com/?p=504</link>
<pubDate>Tue, 05 Feb 2008 09:35:10 +0000</pubDate>
<dc:creator>Chaks</dc:creator>
<guid>http://chakkaradeep.wordpress.com/?p=504</guid>
<description><![CDATA[
My last post on Mock Objects explained briefly about what is Mocking and gave you an example. But t]]></description>
<content:encoded><![CDATA[<p><img src="http://chakkaradeep.files.wordpress.com/2008/01/tdd.png" height="100" width="100" /></p>
<p>My <a href="http://chakkaradeep.wordpress.com/2008/01/25/mock-objects/">last post on Mock Objects</a> explained briefly about what is Mocking and gave you an example. But that example is not explained and thought let me explain and how Mocking plays its part here.</p>
<p>So, revisiting that example,</p>
<pre>[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> AdminTests
{
    <span class="kwrd">private</span> MockRepository mocks;
    <span class="kwrd">private</span> EduAdmin eduAdmin;
    <span class="kwrd">private</span> Bl.IBLAdmin mockAdmin;
    <span class="kwrd">private</span> <span class="kwrd">delegate</span> <span class="kwrd">bool</span> ValidRegisterDelegate(Db.Admin entity);

    [SetUp]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Setup()
    {
         mocks= <span class="kwrd">new</span> MockRepository();

         mockAdmin = mocks.DynamicMock&#60;Bl.IBLAdmin&#62;();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Check_Method_Register()
    {
        AdminEntity inputEntity = <span class="kwrd">new</span> AdminEntity();
        inputEntity.AdminId = <span class="str">“admin”</span>;
        inputEntity.AdminPassword = <span class="str">“admin”</span>;

        Db.Admin dbAdmin=<span class="kwrd">new</span> Educator.DataAccess.Admin
        {
            AdminId = <span class="str">“admin”</span>,
            AdminPwd = <span class="str">“admin”</span>
        };

        With.Mocks(mocks).Expecting(() =&#62;
        {
            Expect
                .Call(mockAdmin.Translate(inputEntity))
                .Return(dbAdmin);

            Expect
                .Call(<span class="kwrd">delegate</span> { mockAdmin.Insert(dbAdmin); })
                .Callback((ValidRegisterDelegate)
                               ((entity) =&#62; { <span class="kwrd">return</span> entity.AdminId == <span class="str">“admin”</span> &#38;&#38; entity.AdminPwd == <span class="str">“admin”</span>; }));

        }).Verify(<span class="kwrd">delegate</span>
       {
           eduAdmin = <span class="kwrd">new</span> EduAdmin(mockAdmin);

           eduAdmin.RegisterAdmin(inputEntity);
       });
    }
}</pre>
<p>To explain the above example, consider this diagram</p>
<p><img src="http://chakkaradeep.wordpress.com/files/2008/02/mock-objects-1.png" alt="mock-objects-1.png" /></p>
<p>(Please consider the line separation, I will come to it later, Ignore the Tests)</p>
<p>So, as the diagram explains, we have,</p>
<p>1) EduAdmin which is our Service Layer (SL)</p>
<p>2) IBLAdmin which is our Business Layer (BL) Interface, and,</p>
<p>3) Database Layer (DL)</p>
<p>The BL interacts with DL to perform database operations and SL sends requests to BL in regard to what needs to be done.</p>
<p>So, what does the above example test function do? Here it is,</p>
<p><img src="http://chakkaradeep.wordpress.com/files/2008/02/flow.png" alt="flow.png" /></p>
<p>Revisiting again the definition of Unit Testing,</p>
<blockquote><p><i>In <a href="http://en.wikipedia.org/wiki/Computer_programming" title="Computer programming">computer programming</a>, <b>unit testing</b> is a procedure used to validate that individual units of <a href="http://en.wikipedia.org/wiki/Source_code" title="Source code">source code</a></i> are working properly. A unit is the smallest testable part of an application.</p>
<p><i>The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy. </i></p></blockquote>
<p>So, testing this <i>RegisterAdmin</i> function involves the use of BL as well DL (via the BL). And also from the first diagram, we do show that each layer is tested against their own tests. So, using Mock Objects, now we come down to,</p>
<p><img src="http://chakkaradeep.wordpress.com/files/2008/02/mock-objects.png" alt="mock-objects.png" /></p>
<p>Since we have mocked our BL, we can now write expectations on how it has to behave and what results it has to give for our Service Layer to work properly :)</p>
<p>To dig deep, we may have something like this,</p>
<p><img src="http://chakkaradeep.wordpress.com/files/2008/02/bl-sl.png" alt="bl-sl.png" /></p>
<p><i>Admin</i> is a class that implements our Interface <i>IBLAdmin</i> and <i>AdminEntity </i>is business type and <i>DB.Admin</i> is a database type.With Mocking, we don't care about the Class but the Interface. <i>EduAdmin </i>is our Service Layer class and it has a function <i>RegisterAdmin</i></p>
<p>So, to <i>RegisterAdmin </i>function to work properly, we have to see that the BL's <i>Translate </i>and <i>Insert </i>functions return proper results and those are nothing but setting expectations on our mock object which is <i>IBLAdmin </i>8) . If you think slowly where we are, you will probably get what is Mocking ;)</p>
<p>Here is that part which sets expectations and tells what should be returned respectively</p>
<pre>        With.Mocks(mocks).Expecting(() =&#62;
        {
            Expect
                .Call(mockAdmin.Translate(inputEntity))
                .Return(dbAdmin);

            Expect
                .Call(<span class="kwrd">delegate</span> { mockAdmin.Insert(dbAdmin); })
                .Callback((ValidRegisterDelegate)
                               ((entity) =&#62; { <span class="kwrd">return</span> entity.AdminId == <span class="str">“admin”</span> &#38;&#38; entity.AdminPwd == <span class="str">“admin”</span>; }));

        }).Verify(<span class="kwrd">delegate</span>
       {
           eduAdmin = <span class="kwrd">new</span> EduAdmin(mockAdmin);

           eduAdmin.RegisterAdmin(inputEntity);
       });</pre>
<p>What does that <i>ValidRegisterDelegate </i>do? It checks whether the input parameters that is being used to invoke <i>Insert </i>function is of expected type and has expected values. Its more of a <i>RhinoMocks </i>feature, so once you start using it, you will get used to it :D . And <i>RhinoMocks </i>follows the <i>Record and ReplayAll</i> method where we set expectations means that we record something and once we say to verify, it replays all the set expectations when invoked.</p>
<p>The expectations we set are very simple. When the <i>Translate </i>function is called with an input parameter of type <i>AdminEntity</i>, return an object of type <i>Db.Admin</i> . Similarly for Insert function, except that we don't return anything.</p>
<p>In the Verify stage, we can see that we create a new instance of our SL by passing the BL Interface object. What are we doing here? Welcome to the world of <a href="http://en.wikipedia.org/wiki/Dependency_Injection" target="_blank"><i>Dependency Injection</i></a> :D . We explicitly tell that - "<i>Hey, here is my BL object which you have to use and please use this</i>". We inject dependency here! So, now the BL object is already in the MockRepository and when we tell our SL to use this object, it means that its going to use the MockRepository object with expectations set on it 8)</p>
<p>I think now things are getting clear and you should be able to understand this diagram way better than earlier :) (which is also shown above)</p>
<p><img src="http://chakkaradeep.wordpress.com/files/2008/02/mock-objects.png" alt="mock-objects.png" /></p>
<p>Coming back to Dependency Injection - You may be wondering that so if  my client uses this SL, will he always have to explicitly tell  that this is my BL and use it? - NO. The way we overcome is using multiple constructors :)</p>
<pre><span class="kwrd">public</span> <span class="kwrd">class</span> EduAdmin
{
     private IBLAdmin blAdmin;

     public EduAdmin(IBLAdmin mockAdmin)
     { blAdmin=mockAdmin;}

      public EduAdmin() : this(new Admin())
     { }
}</pre>
<p>I think thats self explanatory on what we do ;)</p>
<p>Hope this explained how we Mock 8)</p>
<p>If you have any doubts, please do leave your comments and I will try to answer them :)</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[expect-run-verify... Goodbye!]]></title>
<link>http://szczepiq.wordpress.com/?p=58</link>
<pubDate>Fri, 01 Feb 2008 00:03:22 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=58</guid>
<description><![CDATA[Expect-run-verify is the most common pattern in mock frameworks. (update: I called it record-replay-]]></description>
<content:encoded><![CDATA[<p>Expect-run-verify is the most common pattern in mock frameworks. (update: I called it record-replay-verify before - my bad - <b>expect-run-verify</b> is what I really meant).</p>
<p><b>What's wrong with it?</b></p>
<ol>
<li><b>Codebase suffers.</b> Test methods become noisy. I have to expect/record some interactions <b>not</b> because I want to test them but because mocks complain if I don't do it.</li>
<li><b>Doesn't give me a</b> <b>natural test-drive</b>. I prefer when expectations become assertions and appear after execution - it's very intuitive.</li>
<li><b>Tests are fragile.</b> Test driving new functionality that requires additional interaction often breaks all tests. Thanks to the aggressive nature of expect-run-verify.</li>
<li><b>Could give better failures.</b> When expectation becomes assertion, failure shows exact line of code. No more deciphering exception messages - just click on first element on stack trace.</li>
<li><b>Could read better.</b> Separation of stubbing and expectations reads really nicely.</li>
</ol>
<p>Today I discovered <a href="http://moq.googlecode.com">MoQ</a> - little mocking library for .NET. <a href="http://www.clariusconsulting.net/blogs/kzu/archive/2007/12/18/LinqtoMockMoqisborn.aspx">When I read how MoQ was invented</a> I see many similarities with my own thinking process that pushed me to write <a href="http://mockito.googlecode.com">Mockito</a>.</p>
<p align="left"><b>MoQ</b> uses C# 3.0 sugar like lambda expressions. <b>Mockito</b> is a java creature. Both <a href="http://www.clariusconsulting.net/blogs/kzu/archive/2007/12/26/48177.aspx">don't like record/playback</a> model. Mockito goes even further and abandons expect-run-verify.</p>
<p><img src="http://szczepiq.wordpress.com/files/2008/01/dirtyharry.jpeg" alt="dirtyharry" align="left" /></p>
<h3><b>Expect-run-verify...</b></h3>
<h3><b>Goodbye!</b></h3>
<h3><b> </b></h3>
<p>Let me enjoy most natural test-drive: as close to <a href="http://blog.jayfields.com/2008/02/state-based-testing.html">state based testing</a> as possible. Expectations in Mockito are like assertions - good old friends of state based testing.</p>
<p>Java TDDer have several options these days:</p>
<ol>
<li>Using hand crafted stubs/mocks: too much boilerplate, too many lines of code, chaos of stubs.</li>
<li>Using existing mock libraries: less some obscure exceptions it's all <b>expect-run-verify</b> stuff.</li>
<li><a href="http://mockito.googlecode.com"><b>Mockito</b></a>: just try it and tell me what you don't like about it :)</li>
</ol>
<p>I know that <b>many test-infected java people on this planet don't use mock frameworks</b>. They code mocks/stubs from scratch because they find mock libraries too annoying. Mockito offers simplicity and flexibility of hand crafted mocks and yet eliminates so much boilerplate code. I encourage you to try it out.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[10 rules of (unit) testing]]></title>
<link>http://szczepiq.wordpress.com/?p=55</link>
<pubDate>Thu, 31 Jan 2008 01:31:09 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/?p=55</guid>
<description><![CDATA[There you go, those are my 10 rules of (unit) testing. It&#8217;s nothing exciting, really. Everyone]]></description>
<content:encoded><![CDATA[<p><b>There you go, those are my 10 rules of (unit) testing. It's nothing exciting, really. Everyone is so agile these days. Are you agile? I bet you'd say: I was born agile.</b></p>
<p><img src="http://szczepiq.wordpress.com/files/2008/01/10.jpeg" alt="10c" align="left" /></p>
<p>Here I come with my own 10 commandments. I came up with those while doing research on mock frameworks (haven't you heard about <a href="http://mockito.googlecode.com">Mockito</a>, yet? it's the ultimate tdd climax with java mocks). I browsed so much of our project's test code that I feel violated now (codebase is nice, though).</p>
<ol>
<li>If a class is difficult to test, refactor the class. Precisely, split the class if it's too big or if has too many dependencies.</li>
<li>It's not only about test code but I need to say that anyway: Best improvements are those that remove code. Be <a href="http://wuetender-junger-mann.de/wordpress/?p=560">budget-driven</a>. Improve by removing. The only thing better than <a href="http://en.wikipedia.org/wiki/KISS_principle">simple code</a> is no code.</li>
<li>Having 100% line/branch/statement/whatever coverage is not an excuse to write dodgy, duplicated application code.</li>
<li>Again, not only about test code: Enjoy, praise and present decent test code to others. Discuss, refactor and show dodgy test code to others.</li>
<li>Never forget that test code is production code. Test code also loves refactoring.</li>
<li>Hierarchies are difficult to test. Avoid hierarchies to keep things simple and testable. Reuse-by-composition over reuse-by-inheritance.</li>
<li>One assert per test method is a bit fanatical. However, be reasonable and keep test methods small and focused around behavior.</li>
<li>Regardless of what mock framework you use, don't be afraid of creating hand crafted stubs/mocks. Sometimes it's just simpler and the output test code is clearer.</li>
<li>If you have to <a href="http://monkeyisland.pl/2008/01/05/private-method-antipattern">test private method</a> - you've just promoted her to be public method, potentially on different object.</li>
<li>Budget your tests not only in terms of lines of code but also in terms of execution time. Know how long your test run. Keep it fast.</li>
</ol>
<p><b>Number #1</b> is my personal pet. Everybody is so test-driven but so little really care about <b>#1</b> in practice. Best classes, frameworks or systems offer painless testing because they're designed &#38; refactored to be testable. Let the code serve the test and you will produce delightful system.</p>
<p><b>Number #7</b> is a funny one (<i>'Cos we need a little controversy</i>). <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=35578">The</a> <a href="http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html">whole</a> <a href="http://blog.jayfields.com/2008/01/testing-one-expectation-per-test.html">world</a> <a href="http://laribee.com/blog/2007/08/06/one-logical-assertion-per-test/">rolls</a> in the opposite direction. Maybe I just don't get it... yet. Or maybe it's because I paired with young one-assert-per-test guy once. He cunningly kept writing test methods to check if constructor returns not-null value. If I had to play this game and chose my one-<b>something</b>-per-test philosophy I'd steal MarkB's idea: one-behaviour-per-test. After all, It's all about <a href="http://behaviour-driven.org">behavior...</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Passagem de vários parâmetros para método mockado]]></title>
<link>http://thinkabouttests.wordpress.com/2008/01/16/passagem-de-varios-parametros-para-metodo-mockado/</link>
<pubDate>Wed, 16 Jan 2008 16:37:00 +0000</pubDate>
<dc:creator>rodrigomaiabarros</dc:creator>
<guid>http://thinkabouttests.wordpress.com/2008/01/16/passagem-de-varios-parametros-para-metodo-mockado/</guid>
<description><![CDATA[De acordo com o post Passagem de parâmetros para método mockado, a quantidade de parâmetros passa]]></description>
<content:encoded><![CDATA[<p>De acordo com o post <a href="http://thinkabouttests.blogspot.com/2007/12/passagem-de-parametros-para-mtodo.html">Passagem de parâmetros para método mockado</a>, a quantidade de parâmetros passados para o método mockado deve ser igual a do método "de verdade", desta forma encontrei um problema esta manhã:</p>
<p>Tinha um teste para um método, e nele, mockava um método de um outro objeto da seguinte forma:</p>
<p>historicoClienteDao.expects(once()).method("findByFiltros").with(1L, "nome", null, 3L).will(returnValue(historicos));</p>
<p>porém, este método ganhou mais um parâmetro e quando o adicionei, deu erro de compilação:</p>
<p>historicoClienteDao.expects(once()).method("findByFiltros").with(1L, "nome", null, 3L, <span style="font-weight:bold;">true</span>).will(returnValue(historicos));</p>
<p>pois o método with só recebe 4 Constraints.</p>
<p>Aí foi que percebi que ele também recebe um array de Constraints e então o "problema" foi resolvido da seguinte forma:</p>
<p>historicoClienteDao.expects(once()).method("findByFiltros").with(<span style="font-weight:bold;">new Constraint[]{1L, "nome", null, 3L, true}</span>).will(returnValue(historicos));</p>
<p>ps. a ferramenta usada neste exemplo é o JMock.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Mockito]]></title>
<link>http://szczepiq.wordpress.com/2008/01/14/mockito/</link>
<pubDate>Mon, 14 Jan 2008 23:26:22 +0000</pubDate>
<dc:creator>szczepiq</dc:creator>
<guid>http://szczepiq.wordpress.com/2008/01/14/mockito/</guid>
<description><![CDATA[I&#8217;m a mockist but existing mock frameworks just don&#8217;t appeal to me. They spoil my TDD ex]]></description>
<content:encoded><![CDATA[<p>I'm a <a href="http://martinfowler.com/articles/mocksArentStubs.html">mockist</a> but existing mock frameworks just don't appeal to me. They spoil my TDD experience. They harm code readability. I needed something better. That's why I came up with <a href="http://mockito.googlecode.com">Mockito</a>.</p>
<h2>Syntax</h2>
<p>Here is a what I think about mocking syntax:</p>
<ul>
<li><b>Let's keep it simple: interactions are method calls.</b> There is no point in building sophisticated mocking language for method calls in Java. There is already a language for that. It's called Java.</li>
<li><b>The less DSL the better.</b> Interactions are just method calls. Method calls are simple, DSL is complex.</li>
<li><b>No Strings for methods.</b> I spent more time reading code than writing it. Therefore I want the code to be readable. String literals pretending to be methods cannot compete with actual method calls. Even IDEs decorate literals differently so my mind will always adopt the real method call quicker than any literal trying to impersonate a method.</li>
<li><b>No anonymous inner classes.</b> They bring more indentation, more curly brackets, more code, more noise. Did I mention that I spent more time reading code?</li>
<li><b>Painless refactoring.</b> Renaming a method should not break my tests.</li>
</ul>
<p>That's why I really like the syntax of <a href="http://easymock.org">EasyMock</a>.</p>
<h2>Long journey from EasyMock to Mockito</h2>
<p>I was brought up on EasyMock. Normal kids got milk I got classes to test. Over the years on different projects I saw idyllic world of hand crafted stubs being overthrown by EasyMocks. On other project, jmock was doing fine until he got a Chuck's roundhouse kick to the face by EasyMock. Finally, I saw resentment to EasyMock and triumphatic comeback of hand crafted stubs... Sometimes the resentment to EasyMock was a bit naive ("My class has 10 dependencies and is difficult to test. Therefore EasyMock sucks"). Sometimes it was clearly righteous...</p>
<p>Here is what I wanted to achieve with Mockito so that it suits me better in test-driving code the way I like:</p>
<div style="text-align:center;"><img src="http://szczepiq.wordpress.com/files/2008/01/tdd.jpg" alt="tdd" /></div>
<p><b>Focused testing.</b> Should let me focus test methods on specific behavior/interaction. Should minimize distractions like expecting/recording irrelevant interactions.</p>
<p><b>Separation of stubbing and verification</b>. Should let me code in line with intuition: stub before execution, selectively verify interactions afterwards. I don't want any verification-related code before execution.</p>
<p><b>Explicit language.</b> Verification and stubbing code should be easy to discern, should distinguish from ordinary method calls / from any supporting code / assertions.</p>
<p><b>Simple stubbing model. </b>Should bring the simplicity of good old hand crafted stubs without the burden of actually implementing a class. Rather than verifying stubs I want to focus on testing if stubbed value is used correctly.<br />
<b></b></p>
<p><b>Only one type of mock, one way of creating mocks.</b> So that it's easy to share setup.</p>
<p><b>No framework-supporting code.</b> No record(), replay() methods, no alien control/context objects. These don't bring any value to the game.</p>
<p><b>Slim API.</b> So that anyone can use it efficiently and produce clean code. API should push back if someone is trying to do something too smart: if the class is difficult to test - refactor the class.</p>
<p><b>Explicit errors. </b>Verification errors should always point stack trace to failed interaction. I want to click on first stack element and navigate to failed interaction.</p>
<p><b>Clean stack trace.</b> Part of TDDing is reading stack traces. It's Red-Green-Refactor after all - I've got stack trace when it's red. Stack trace should always be clean and hide irrelevant internals of a library. Although modern IDE can help here, I'd rather not depend on IDE neither on competence in using IDE...</p>
<div style="text-align:center;"><img src="http://szczepiq.wordpress.com/files/2008/01/split.gif" alt="road split" /></div>
<p>EasyMock is a decent piece of software, credits go to kick-ass people who wrote it. I had to fix it, though :). I've even submitted some patches to address inflexibility of mock modes but they never made it to the trunk. I had more radical ideas so I forked the project removing, refactoring and rewriting loads of code. <a href="http://mockito.googlecode.com">Enjoy.</a></p>
<p>(I refactored this page a since I wrote it, precisely I got rid of lengthly mock framework comparison).</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JMockit - Mockando um Método Estático]]></title>
<link>http://thinkabouttests.wordpress.com/2007/12/14/jmockit-mockando-um-metodo-estatico/</link>
<pubDate>Fri, 14 Dec 2007 15:59:00 +0000</pubDate>
<dc:creator>rodrigomaiabarros</dc:creator>
<guid>http://thinkabouttests.wordpress.com/2007/12/14/jmockit-mockando-um-metodo-estatico/</guid>
<description><![CDATA[É com grande felicidade que consegui, nesta manhã de sexta, mockar um método estático, p&amp;#@ ]]></description>
<content:encoded><![CDATA[<p>É com grande felicidade que consegui, nesta manhã de sexta, mockar um método estático, p&#38;#@ que p@$%&#38;, sensacional.</p>
<p>O nome do cara é <a href="https://jmockit.dev.java.net/">JMockit</a></p>
<p>Bem, o meu exemplo é bem simples:</p>
<p>Criei uma classe que tem somente um método estático, é esta classe que quero mockar:</p>
<p>public class ClasseUtil {</p>
<p>public static int metodoEstatico()<br />
{<br />
return 1;<br />
}</p>
<p>}</p>
<p>Então, uma classe que utiliza este método:</p>
<p>public class ClasseFuncionalidade {</p>
<p>public static int metodoLocal()<br />
{<br />
return ClasseUtil.metodoEstatico();<br />
}<br />
}</p>
<p>Por fim, a classe de teste:</p>
<p>public class ClasseFuncionalidadeTeste{</p>
<p>public static class MockClasseUtil{</p>
<p>public static int metodoEstatico()<br />
{<br />
return 0;<br />
}<br />
}</p>
<p>@Before<br />
public void prepare(){<br />
Mockit.redefineMethods(ClasseUtil.class, MockClasseUtil.class);<br />
}</p>
<p>@After<br />
public void finalize(){<br />
Mockit.restoreAllOriginalDefinitions();<br />
}</p>
<p>@Test<br />
public void metodoLocal(){<br />
assertEquals(0, ClasseFuncionalidade.metodoLocal());<br />
}</p>
<p>}</p>
<p>Perceba que criei uma outra classe (inner class) chamada MockClasseUtil, com um método (metodoEstatico) de mesma assinatura do método da classe ClasseUtil, porém o retorno é diferente (No original é 1 e no falso é 0).</p>
<p>Redefino os métodos da classe real pelos da classe mock:</p>
<p>@Before<br />
public void prepare(){<br />
Mockit.redefineMethods(ClasseUtil.class, MockClasseUtil.class);<br />
}</p>
<p>Se fosse no JUnit3, poderia usar o método setUp para invocar o redefineMethods.</p>
<p>E para voltar "ao normal":</p>
<p>@After<br />
public void finalize(){<br />
Mockit.restoreAllOriginalDefinitions();<br />
}</p>
<p>A única dificuldade foi "ver" que o comando "-javaagent:jmockit.jar" deve ser passado como parâmetro para a JVM:</p>
<p>No eclipse é só fazer isso, na hora de rodar o teste:</p>
<p><a href="http://bp0.blogger.com/_4x-irBbGvFc/R2Kpz5YNkdI/AAAAAAAAABg/rBsvO2BGSoA/s1600-h/parametro+jmockit.JPG"><img src="http://bp0.blogger.com/_4x-irBbGvFc/R2Kpz5YNkdI/AAAAAAAAABg/rBsvO2BGSoA/s320/parametro+jmockit.JPG" style="display:block;text-align:center;cursor:pointer;margin:0 auto 10px;" border="0" /></a></p>
<p>ou isso, para rodar com test suite ou qualquer outro lugar:</p>
<p><a href="http://bp3.blogger.com/_4x-irBbGvFc/R2Kp5pYNkeI/AAAAAAAAABo/AJiTmtwyxxI/s1600-h/parametro+jmockit+jvm.JPG"><img src="http://bp3.blogger.com/_4x-irBbGvFc/R2Kp5pYNkeI/AAAAAAAAABo/AJiTmtwyxxI/s320/parametro+jmockit+jvm.JPG" style="display:block;text-align:center;cursor:pointer;margin:0 auto 10px;" border="0" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[JMock versus Classes Concretas 2 - A Missão]]></title>
<link>http://thinkabouttests.wordpress.com/2007/12/06/jmock-versus-classes-concretas-2-a-missao/</link>
<pubDate>Thu, 06 Dec 2007 11:20:00 +0000</pubDate>
<dc:creator>rodrigomaiabarros</dc:creator>
<guid>http://thinkabouttests.wordpress.com/2007/12/06/jmock-versus-classes-concretas-2-a-missao/</guid>
<description><![CDATA[Me recuperando da decepção da incompatibilidade de versões do JMock, ví que o JMock 1 pode mocka]]></description>
<content:encoded><![CDATA[<p>Me recuperando da decepção da incompatibilidade de versões do JMock, ví que o JMock 1 pode mockar classes concretas.</p>
<p>Baixei o jmock-cglib-version.jar, como diz no link abaixo:</p>
<p><a href="http://www.jmock.org/jmock1-cglib.html">http://www.jmock.org/jmock1-cglib.html</a></p>
<p>e funcionou.</p>
<p>A única limitação é que não pode ser uma classe final.</p>
<p>JMock acaba de recuperar seus pontos.</p>
<p>Thanks, Nat Pryce.</p>
]]></content:encoded>
</item>

</channel>
</rss>
