<?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>Push cx &#187; unit tests</title>
	<atom:link href="http://push.cx/tag/unit-tests/feed" rel="self" type="application/rss+xml" />
	<link>http://push.cx</link>
	<description>A traveling geek&#039;s blog on development, games, and the web</description>
	<lastBuildDate>Fri, 14 Oct 2011 10:24:13 +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>Simple Ruby Mocking</title>
		<link>http://push.cx/2007/simple-ruby-mocking</link>
		<comments>http://push.cx/2007/simple-ruby-mocking#comments</comments>
		<pubDate>Fri, 17 Aug 2007 20:15:29 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/simple-ruby-mocking</guid>
		<description><![CDATA[I mentioned at the end of my last post on testing that I wrote some code to do mocking for my unit tests in Ruby. Writing a small mock library was very much reinventing the wheel, but I needed to do it to earn a deeper understanding of mocks. I&#8217;m writing some code (&#8220;Fetcher&#8221;) to [...]]]></description>
			<content:encoded><![CDATA[<p>
I mentioned at the end of my <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3B1c2guY3gvMjAwNy9maXh0dXJlcy1pbi1ydWJ5LXVuaXQtdGVzdHM=">last post on testing</a> that I wrote some code to do mocking for my unit tests in Ruby. Writing a small mock library was very much reinventing the wheel, but I needed to do it to earn a deeper understanding of mocks. 
</p>

<p>
I&#8217;m writing some code (&#8220;Fetcher&#8221;) to talk to a POP3 server, fetch mail, and pass it off to another process. One of the tests deals with what happens when the POP3 server is down or otherwise unreachable.
</p>

<pre>&nbsp;
def test_setup_server_down
  pop3 = Mock.<span style="">new</span>
  pop3.<span style="">expect</span><span style="color: #66cc66;">&#40;</span>:<span style="color: #000000; font-weight: bold;">new</span>, <span style="color: #66cc66;">&#91;</span>MAIL_SERVER, MAIL_POP3_PORT<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span> raise Timeout::<span style="color: #006600;">Error</span>.<span style="">new</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"execution expired"</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#125;</span>
  f = Fetcher.<span style="">new</span><span style="color: #66cc66;">&#40;</span>pop3<span style="color: #66cc66;">&#41;</span>
  <span style="color: #808080; font-style: italic;"># further assertions that f acts correctly</span>
<span style="color: #b1b100;">end</span></pre>

<p>
This says that the Mock object expects a call to the new method with the given arguments, and when the call happens it runs the block. The block could return anything, but in this case it raises the same error as <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5ydWJ5LWRvYy5vcmcvc3RkbGliL2xpYmRvYy9uZXQvcG9wL3Jkb2MvY2xhc3Nlcy9OZXQvUE9QMy5odG1s">Net::Pop3</a> does when it can&#8217;t contact the server. After that the test can go on to make whatever assertions it needs to verify that the exception was handled properly.
</p>

<p>
The Mock object has a list of <kbd>calls</kbd> it expects to see and keeps a list of how it&#8217;s been <kbd>called</kbd> (yes, this could just be one list with an index but I thought it was mentally simpler this way). The test sets up what calls it should <kbd>expect</kbd> to see with what arguments (or blank for any) and block to run (or blank for none). When a method is called on the mock object, <kbd>method_missing</kbd> logs the call and executes the given block (raising a fuss if the call didn&#8217;t match what it expected). 
</p>

<pre>&nbsp;
class Mock
  attr_reader :calls, :called
&nbsp;
  <span style="color: #808080; font-style: italic;"># the stub arg makes it just record all calls</span>
  def initialize
    <span style="color: #0000ff;">@calls</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    <span style="color: #0000ff;">@called</span> = <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  <span style="color: #808080; font-style: italic;"># Pass nil for args to ignore the actual args in the call.</span>
  <span style="color: #808080; font-style: italic;"># Proc is optional; default is empty proc returning nil.</span>
  def expect<span style="color: #66cc66;">&#40;</span>method, *args, &amp;proc<span style="color: #66cc66;">&#41;</span>
    <span style="color: #0000ff;">@calls</span> &lt;&lt; <span style="color: #66cc66;">&#123;</span>:method =&gt; method, :args =&gt; args.<span style="">first</span>, :proc =&gt; <span style="color: #66cc66;">&#40;</span>proc <span style="color: #b1b100;">or</span> Proc.<span style="">new</span><span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#125;</span>
  <span style="color: #b1b100;">end</span>
&nbsp;
  def method_missing<span style="color: #66cc66;">&#40;</span>method, *args<span style="color: #66cc66;">&#41;</span>
    <span style="color: #0000ff;">@called</span> &lt;&lt; <span style="color: #66cc66;">&#123;</span>:method =&gt; method, :args =&gt; args<span style="color: #66cc66;">&#125;</span>
&nbsp;
    expect = <span style="color: #0000ff;">@calls</span>.<span style="">shift</span>
    raise <span style="color: #ff0000;">"Unexpected mock call #{method.to_s}(#{args.join(', ')})"</span> <span style="color: #b1b100;">if</span> expect.<span style="">nil</span>?
    raise <span style="color: #ff0000;">"Wrong mock call #{method.to_s}(#{args.join(', ')}); expected #{expect[:method]}(#{expect[:args].join(', ')})"</span> <span style="color: #b1b100;">if</span> method != expect<span style="color: #66cc66;">&#91;</span>:method<span style="color: #66cc66;">&#93;</span> <span style="color: #b1b100;">or</span> <span style="color: #66cc66;">&#40;</span>expect<span style="color: #66cc66;">&#91;</span>:args<span style="color: #66cc66;">&#93;</span> != nil <span style="color: #b1b100;">and</span> args != expect<span style="color: #66cc66;">&#91;</span>:args<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span>
    expect<span style="color: #66cc66;">&#91;</span>:proc<span style="color: #66cc66;">&#93;</span>.<span style="">call</span><span style="color: #66cc66;">&#40;</span>*args<span style="color: #66cc66;">&#41;</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
It&#8217;s a straightforward little object, and I also added some code to raise a fuss if expected calls weren&#8217;t made. This does have the downside that any tests defining their own <kbd>teardown</kbd> need to call <kbd>super</kbd>.
</p>

<pre>&nbsp;
class Mock
  def fail_if_not_empty
    <span style="color: #808080; font-style: italic;"># Empty the call stack so that this obj doesn't throw errors for</span>
    <span style="color: #808080; font-style: italic;"># every later test between now and this object getting gc'd</span>
    calls, <span style="color: #0000ff;">@calls</span> = <span style="color: #0000ff;">@calls</span>, <span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span>
    raise <span style="color: #ff0000;">"Mock calls uncalled: n"</span> + calls.<span style="">collect</span> <span style="color: #66cc66;">&#123;</span> |call| <span style="color: #ff0000;">"#{call[:method]}(#{call[:args]} { #{call[:proc] })"</span> <span style="color: #66cc66;">&#125;</span>.<span style="">join</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">" "</span><span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">unless</span> calls.<span style="">empty</span>?
  <span style="color: #b1b100;">end</span>
end
&nbsp;
class Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  def teardown
    finish_mocks
  <span style="color: #b1b100;">end</span>
&nbsp;
  def finish_mocks
    ObjectSpace.<span style="">each_object</span><span style="color: #66cc66;">&#40;</span>Mock<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span> |m|
      <span style="color: #000066;">m</span>.<span style="">fail_if_not_empty</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
This has been a handy piece of code to test the code I&#8217;ve written in the last two weeks, but it&#8217;s not good enough. I have to use a technique called dependency injection to test <kbd>Fetcher.new</kbd>, where the outside code passes it a POP3 object instead of its <kbd>initialize</kbd> just using Net::POP3. Useful for testing, but my code is badly repetitive when all the instantiation calls have to do this exact same setup. (As an aside, Jacob Proffitt recently started an interesting conversation on <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMDcvZGVwZW5kZW5jeS1pbmplY3Rpb24uYXNweA==">dependency injection</a>, took <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMTUvcmlwcGluZy1vbi1kaS5hc3B4">criticism</a>, and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NjcnVmZnlsb29raW5nY2F0aGVyZGVyLmNvbS9hcmNoaXZlLzIwMDcvMDgvMTYvdGlsdGluZy1hdC13aW5kbWlsbHMuYXNweA==">responded</a>. Good reading.)
</p>

<p>
I was pondering how to extend the Mock object to let me mock class methods (eg a call to <kbd>Net::POP3.new</kbd>) when I realized I&#8217;d gone as far as I should down the do-it-yourself road. I&#8217;d heard of <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2hhLnJ1Ynlmb3JnZS5vcmcv">Mocha</a> and it took me all of ten minutes to think to look at its <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2NoZWF0LmVycnRoZWJsb2cuY29tL3MvbW9jaGEv">cheat sheet</a> where that&#8217;s the first example.
</p>

<p>
After spending two hours or so writing and tweaking this code, the best thing for it is to be thrown away. I&#8217;ve learned about mocking by doing it and I&#8217;m better-prepared to understand someone else&#8217;s larger and better library.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=253" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/simple-ruby-mocking/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Fixtures in Ruby Unit Tests</title>
		<link>http://push.cx/2007/fixtures-in-ruby-unit-tests</link>
		<comments>http://push.cx/2007/fixtures-in-ruby-unit-tests#comments</comments>
		<pubDate>Thu, 12 Jul 2007 21:45:47 +0000</pubDate>
		<dc:creator>Peter Harkins</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[fixtures]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>

		<guid isPermaLink="false">http://push.cx/2007/fixtures-in-ruby-unit-tests</guid>
		<description><![CDATA[I&#8217;m writing some Ruby scripts that sort and store lots of small files. After a day or two of hacking I had the basic code working, ran through a few thousand files, and a malformed file blew up the sorter. That was OK, the sorter was intentionally naive and lacking in error handling; I wanted [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;m writing some Ruby scripts that sort and store lots of small files. After a day or two of hacking I had the basic code working, ran through a few thousand files, and a malformed file blew up the sorter. That was OK, the sorter was intentionally naive and lacking in error handling; I wanted it to hack it together and try out a few approaches before committing to serious development.
</p>

<p>
Now it&#8217;s time to treat it as real code, which means getting it under test. Tests are especially useful for ensuring tricky edge cases like malformed input don&#8217;t quietly break during other changes. When I started writing unit tests for the sorter I wanted fixtures similar to the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21hbnVhbHMucnVieW9ucmFpbHMuY29tL3JlYWQvY2hhcHRlci8yNg==">Rails fixtures</a> so I could write:
</p>

<pre>&nbsp;
<span style="color: #000066;">require</span> File.<span style="">dirname</span><span style="color: #66cc66;">&#40;</span>__FILE__<span style="color: #66cc66;">&#41;</span> + <span style="color: #ff0000;">'/../test_helper'</span>
<span style="color: #000066;">require</span> <span style="color: #ff0000;">'message'</span>
&nbsp;
class MessageTest &lt; Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  fixtures :message
&nbsp;
  def test_initialization
    f = Message.<span style="">new</span> message<span style="color: #66cc66;">&#40;</span>:good<span style="color: #66cc66;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># assert the object was parsed correctly, etc.</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
The basic usage is <kbd>fixtures :type</kbd> to load the data and create the named function (in this case, <kbd>message</kbd>)  for fetching data. First, I wrote some <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3lhbWwub3JnL3N0YXJ0Lmh0bWw=">YAML</a> fixtures for my data and put them in <kbd>test/fixtures/message.yaml</kbd>. You can see the <kbd>:good</kbd> key in use here:
</p>

<pre>
good: |
  [the body of a good message here]
missing_header: |
  [more text]
bad_checksum: |
  [more text]
</pre>

<p>
Because I&#8217;m parsing textfiles my fixtures look pretty simple, but the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5ydWJ5LWRvYy5vcmcvc3RkbGliL2xpYmRvYy95YW1sL3Jkb2MvaW5kZXguaHRtbA==">YAML library</a> for Ruby makes serialization of any very easy.
</p>

<p>
So here&#8217;s the code I put in <kbd>test/test_helper.rb</kbd> to set this up. I really like the <kbd>[list].flatten.each</kbd> idiom so the call from the unit test class can cleanly pass one or more types, eg: <kbd>fixtures :message</kbd> and <kbd>fixtures :message, :user</kbd>.
</p>

<pre>&nbsp;
class Test::<span style="color: #006600;">Unit</span>::<span style="color: #006600;">TestCase</span>
  <span style="color: #0000ff;">@@fixtures</span> = <span style="color: #66cc66;">&#123;</span><span style="color: #66cc66;">&#125;</span>
  def self.<span style="">fixtures</span> list
    <span style="color: #66cc66;">&#91;</span>list<span style="color: #66cc66;">&#93;</span>.<span style="">flatten</span>.<span style="">each</span> <span style="color: #b1b100;">do</span> |fixture|
      self.<span style="">class_eval</span> <span style="color: #b1b100;">do</span>
        <span style="color: #808080; font-style: italic;"># add a method name for this fixture type</span>
        define_method<span style="color: #66cc66;">&#40;</span>fixture<span style="color: #66cc66;">&#41;</span> <span style="color: #b1b100;">do</span> |item|
          <span style="color: #808080; font-style: italic;"># load and cache the YAML</span>
          <span style="color: #0000ff;">@@fixtures</span><span style="color: #66cc66;">&#91;</span>fixture<span style="color: #66cc66;">&#93;</span> ||= YAML::<span style="color: #006600;">load_file</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"test/fixtures/#{fixture.to_s}.yaml"</span><span style="color: #66cc66;">&#41;</span>
          <span style="color: #0000ff;">@@fixtures</span><span style="color: #66cc66;">&#91;</span>fixture<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#91;</span>item.<span style="">to_s</span><span style="color: #66cc66;">&#93;</span>
        <span style="color: #b1b100;">end</span>
      <span style="color: #b1b100;">end</span>
    <span style="color: #b1b100;">end</span>
  <span style="color: #b1b100;">end</span>
end</pre>

<p>
(Note to Rails coders: I deliberately left out the pluralization, I like having the File class in <kbd>file.rb</kbd> with the fixtures in <kbd>text/fixtures/file.rb</kbd> and the database table named <kbd>file</kbd> and so on. I don&#8217;t mind Rails&#8217; convention of pluralizing to &#8220;files&#8221; in the latter two examples, but I&#8217;d rather have a single identifier.)
</p>

<p>
Last night at the <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3J1ZG9scGhoZXJpbmdzb2NpZXR5Lm9yZy9pbmRleC5waHA/dGl0bGU9TWFpbl9QYWdl">Rudolph Hering Society</a> meeting <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuaWFuYmlja2luZy5vcmc=">Ian Bicking</a> and <a href="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3Blb3BsZS5jcy51Y2hpY2Fnby5lZHUvfnZhcm1hYS8=">Atul Varma</a> explained mocking to me. I wrote a (very) little Ruby this morning to do mocking and I&#8217;ll post that in a day or two when I&#8217;m sure I didn&#8217;t do it too badly.
</p> <img src="http://push.cx/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=250" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://push.cx/2007/fixtures-in-ruby-unit-tests/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

