<?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>unit-testing &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/unit-testing/</link>
	<description>Feed of posts on WordPress.com tagged "unit-testing"</description>
	<pubDate>Wed, 22 May 2013 12:43:54 +0000</pubDate>

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

<item>
<title><![CDATA[TDD and upfront design]]></title>
<link>http://craftingcode.org/2013/03/31/tdd-and-upfront-design/</link>
<pubDate>Sun, 31 Mar 2013 21:29:34 +0000</pubDate>
<dc:creator>larsro81</dc:creator>
<guid>http://craftingcode.org/2013/03/31/tdd-and-upfront-design/</guid>
<description><![CDATA[In TDD we talk about emergent design almost as if it is something which happens by magic simply beca]]></description>
<content:encoded><![CDATA[<p>In TDD we talk about emergent design almost as if it is something which happens by magic simply because of the way the code is written. This is obviously not true, there is no magic in programming, the design happens as part of the refactoring step. We refactor our code into a good design. This forces us to write code that is easy (and safe) to change simply because we change it often. This is in my opinion the biggest advantage to TDD.</p>
<p>There is also an interesting implication to this, it means that the traditional order, design -&#62; code -&#62; test, is switch around so we test -&#62; code-&#62; design (refactor) when we do TDD.</p>
<p>This often is interpreted as: “I am not allowed to do any upfront design at all.” This notion actually contains two fallacies about TDD:</p>
<ul>
<li>First, TDD is not like Extreme Programing where either you are doing it or you are not. TDD is Fuzzier with room for doing things in different ways, so it fits both your style of work and the project you are doing.</li>
<li>Second, the purpose of TDD is to control the gap between the point at which you do something and the point at which you figure out if that something actually works. If you do a bit of design and then immediately write a test that essentially is the first user of that design then I don’t see a problem with that.</li>
</ul>
<p>Where you might start to get in trouble is if you try and combine TDD with<a href="http://en.wikipedia.org/wiki/Big_Design_Up_Front"> big upfront design</a>, where you map out all the classes and all their interactions. When you do that then the gap between the design and the code which uses that design becomes too big.</p>
<p>If we jump back to the test -&#62; code -&#62; design, I mentioned earlier, in truth that is actually a little too simple. Since this is not a linear process, it is circular. What it actually looks like is this:</p>
<p style="text-align:center;"><a href="http://craftingcodedotorg.files.wordpress.com/2013/03/tddcyclesmall.png"><img class=" wp-image-56 aligncenter" alt="TDDCycleSmall" src="http://craftingcodedotorg.files.wordpress.com/2013/03/tddcyclesmall.png?w=300&#038;h=267" width="300" height="267" /></a></p>
<p>Therefore, if you want to start with doing a bit of design upfront, all you are really doing is starting your first cycle at the refactor step, instead of the test step. Considering you will do several 100s to 1000s cycles though this before any larger project is done, I doubt anybody we hold it against you if you started that first on out at the “wrong” place in the process.</p>
<p><span style="line-height:1.714285714;font-size:1rem;">The design you do before you start should not be set in stone. It is very likely to change before you are done. Think of it as a direction to drive in, not a turn by turn map instruction to get to the goal.</span></p>
<div>
<p>For the <a href="http://craftingcode.org/category/symbolic-calculator-series/">symbolic calculator</a> I did a bit of upfront design. I decided I was going to use parsing trees for doing the evaluation of the expressions. This design looks something like this:</p>
<p style="text-align:center;"><a href="http://craftingcodedotorg.files.wordpress.com/2013/03/parsetreeuml.png"><img class="size-medium wp-image-57 aligncenter" alt="ParseTreeUml" src="http://craftingcodedotorg.files.wordpress.com/2013/03/parsetreeuml.png?w=300&#038;h=163" width="300" height="163" /></a></p>
<p>That was it. That was the extent of the upfront design considerations I did before I started the project.</p>
<p>It is also clear from the <a href="http://craftingcode.org/2013/03/30/symbolic-calculator-part-2-getting-started/">first coding post</a> in the series that no classes are created until either they are needed by a test or we refactor existing (test covered) code into fitting this design. So the design is not used to generate any skeleton code.</p>
<p>I have tried this out on everything from small TDD katas to multi-tiered systems. What I found is that the bigger and more complex the system the more it helps me to do a little upfront design before I start. With smaller and less complex things it is usually a wast of time.With that out of the way I think it is time to get back to actually coding something…</p>
</div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[The Benefits of Unit Testing Pt. 1 - Isolates Development]]></title>
<link>http://jakeradakovich.com/2013/03/30/the-benefits-of-unit-testing-pt-1-isolation/</link>
<pubDate>Sat, 30 Mar 2013 05:31:37 +0000</pubDate>
<dc:creator>Jake Radakovich</dc:creator>
<guid>http://jakeradakovich.com/2013/03/30/the-benefits-of-unit-testing-pt-1-isolation/</guid>
<description><![CDATA[Judging from the conversations that I have had with many developers, the benefits of unit testing ar]]></description>
<content:encoded><![CDATA[<p>Judging from the conversations that I have had with many developers, the benefits of unit testing are not immediately apparent.  Understanding the utility of unit testing was a slow, incremental process for me.  In this post, I will be using a simple <code>Circle</code> class to demonstrate my early development process, and then I will show how unit testing has vastly improved this process.  Let&#8217;s jump right in.  </p>
<p>When I first started writing code, I would have begun by writing the <code>Circle</code> class as shown below.</p>
<p></p>
<h5>Circle.java</h5>
<pre class="brush: java; title: ; notranslate" title="">
public class Circle
{
    private int radius;

    public Circle(int radius)
    {
        this.radius = radius;
    }

    public double getArea()
    {
        return 3.14 * this.radius * this.radius;
    }

    public double getCircumference()
    {
        return 2 * 3.14 * this.radius;
    }
}

</pre>
<p>Next, I would have written a main class to instantiate and execute the methods of my new class.</p>
<h5>Main.java</h5>
<pre class="brush: java; title: ; notranslate" title="">
public class Main
{
    public static void main(String... args)
    {
        Circle cirlce = new Circle(5);

        System.out.println(&#34;Area: &#34; + System.out.println(circle.getArea());
        System.out.println(&#34;Circumference: &#34; + System.out.println(circle.getCircumference());
    }
}
</pre>
<p>When I was sure that my class worked the way that I wanted, I would have started on my next class. Depending on the circumstance, when I was finished developing my application, I would have deleted the main class or modified the main class to execute the program.</p>
<p>This approach proved problematic when working on a large web application. I would either pick a place in code that I could easily trigger from an unrelated user interface and test the new code much the same way as shown above, or I would develop the new feature from the top down, executing the new code from the user interface at periodic intervals to make sure my code was working as expected.  Of course, the latter approach required that the user interface be in place.</p>
<p>This is a horrible approach, and this problem was the first to show me the practicality of unit testing. Unit testing allows you to isolate the code you are writing and independently execute the code outside the scope of the entire application.</p>
<p></p>
<p>With unit testing, starting new development is as simple as starting to write tests.  In the case of the <code>Circle</code> class, I begin by writing the basic structure of the class.</p>
<p></p>
<h5>Basic Circle.java</h5>
<pre class="brush: java; title: ; notranslate" title="">
public class Circle
{
    public Circle(int radius)
    {
        
    }
}
</pre>
<p>I realize that I have written the skeleton of my class before writing my test.  This does not conform to <a href="http://en.wikipedia.org/wiki/Test-driven_development" title="test-driven development" target="_blank">test-driven development</a>, but I like to take this initial step so I don&#8217;t get errors or warnings in my IDE.  I am now free to start writing my tests using <a href="http://junit.org/" title="JUnit" target="_blank">JUnit</a>.</p>
<p></p>
<p>I know that if the radius of the circle is negative, I want to throw an <code>IllegalArgumentException</code>. I first write the test that asserts that we expect an error when instantiating a <code>Circle</code> with a negative radius.</p>
<p></p>
<h5>TestCircle.java</h5>
<pre class="brush: java; title: ; notranslate" title="">
@Test(expected = IllegalArgumentException.class)
public void testCircle()
{
    Circle circle = new Circle(-1);
}
</pre>
<p>Of course, this test will fail, but I am now free to continue developing my <code>Circle</code> class outside of the scope of the application</p>
<p></p>
<h5>Implementing the constructor in Circle.java</h5>
<pre class="brush: java; title: ; notranslate" title="">
public class Circle
{
    private int radius;

    public Circle(int radius)
    {
        if(radius &#60; 0)
        {
            throw new IllegalArgumentException(&#34;A circle's radius cannot be less than zero.&#34;);
        }

        this.radius = radius;
    }
}
</pre>
<p>Now this test will pass, and I can move on to developing more of the <code>Circle</code> class.
<p></p>
<p>To drive this point home, let&#8217;s consider that we are developing the General Geometry Calculator.  This calculator will be a web application that allows users to calculate various geometrical properties of shapes.  With unit testing, I don&#8217;t have to have the user interface designed and implemented, and I don&#8217;t even have to start my development server.  I can simply start working on the <code>Circle</code> class and use it when I am ready.</p>
<p></p>
<p>I hope I have demonstrated how developing code in isolation is beneficial. I don&#8217;t think isolating code development is the most important benefit of unit testing, but it is the first practical aspect of unit testing that I experienced.  It allows a developer to construct various parts of an application independently without regard to other areas of the application.  <a href="http://jakeradakovich.wordpress.com/2013/04/06/the-benefits-of-unit-testing-pt-2-encouraging-analysis/" title="Part Two">Part two</a> of this series will describe how unit testing forces developers to analyze their code more closely.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Running Jasmine Tests Hosted in IIS Express as part of a TeamCity Build]]></title>
<link>http://roysvork.wordpress.com/2013/03/29/running-jasmine-tests-hosted-in-iis-express-as-part-of-a-teamcity-build/</link>
<pubDate>Fri, 29 Mar 2013 23:10:05 +0000</pubDate>
<dc:creator>roysvork</dc:creator>
<guid>http://roysvork.wordpress.com/2013/03/29/running-jasmine-tests-hosted-in-iis-express-as-part-of-a-teamcity-build/</guid>
<description><![CDATA[This week I&#8217;ve been having a lot of fun setting up a CI server for our project. I went with Te]]></description>
<content:encoded><![CDATA[<p>This week I&#8217;ve been having a lot of fun setting up a CI server for our project. I went with <a href="http://www.jetbrains.com/teamcity/">TeamCity</a> as it&#8217;s a great product and there&#8217;s oodles of documentation out there so setting things up is a doddle. I chose to set up our server on a Windows Azure virtual machine, there&#8217;s a guide here on how to get started if you&#8217;re interested:</p>
<ul>
<li><a href="http://blog.virtew.com/2012/08/18/setup-teamcity-on-an-azure-virtual-machine-for-windows-8-metro-style-apps/" rel="nofollow">http://blog.virtew.com/2012/08/18/setup-teamcity-on-an-azure-virtual-machine-for-windows-8-metro-style-apps/</a></li>
</ul>
<p>I promptly set about creating a configuration that would run all my unit tests, but ran into a small problem when it came to the JavaScript side of things.</p>
<p>I&#8217;d designed my test project to re-use the bundle config from my web app, and then used MVC to render the test runner. I thought I had been very clever&#8230; I had the benefit of picking up new source files as and when I created them; no need to constantly add references to new scripts in the test project.</p>
<p>When I came to run these tests as part of my TeamCity build process however, I realised that I needed to compile and host my tests in order to run them&#8230; not something that is easily achieveable as part of a normal build process. We don&#8217;t always know where our code will be checked out to, and we may need to do this in a way that will work for multiple configurations.</p>
<p>Not to worry though, with a bit of coding, we can make this work.</p>
<div style="height:1.4em;visibility:hidden;">spc</div>
<h3>The requirements</h3>
<p>Our chain of events needs to run as follows:</p>
<ul>
<li><span style="line-height:13px;">Build the test project</span></li>
<li>Start IIS Express to host the tests</li>
<li>Run the tests and capture the results</li>
<li>Shut down IIS Express</li>
</ul>
<div style="height:1.4em;visibility:hidden;">spc</div>
<p>Seems simple enough. Dan Merino has a great post on how to use the jasmine team city reporter in conjunction with Phantom.JS to run our tests and process the results:</p>
<ul>
<li><span style="line-height:13px;"><a href="http://blog.danmerino.com/continuos-integration-ci-for-javascript-jasmine-and-teamcity/" rel="nofollow">http://blog.danmerino.com/continuos-integration-ci-for-javascript-jasmine-and-teamcity/</a></span></li>
</ul>
<p>It&#8217;s also pretty easy to run IIS express from the command line (of course you&#8217;ll need to have iis express installed on your build server first):</p>
<ul>
<li><a href="http://www.iis.net/learn/extensions/using-iis-express/running-iis-express-from-the-command-line" rel="nofollow">http://www.iis.net/learn/extensions/using-iis-express/running-iis-express-from-the-command-line</a></li>
</ul>
<p>Where it all comes unstuck however, is that we need to start IIS express after we&#8217;ve built our code, but before running our tests. Then we need to stop it again after our tests have run. There&#8217;s no built in way to do this with team city however, we need to script this in some way or write an app to help us.</p>
<div style="height:1.4em;visibility:hidden;">spc</div>
<p><strong>Phantom Express</strong><br />
First we need to configure a runner in our test project that will output the results in a form that TeamCity can interpret, we can do this using the TeamCity reporter:</p>
<pre>&#60;html&#62;
&#60;head&#62;
    &#60;title&#62;Jasmine Spec Runner&#60;/title&#62;

    &#60;link rel="shortcut icon" type="image/png" href="/Content/jasmine/jasmine_favicon.png"&#62;
    &#60;link rel="stylesheet" type="text/css" href="/Content/jasmine/jasmine.css"&#62;

    @Html.Partial("TestIncludes");

    &#60;script type="text/javascript"&#62;
        (function () {

            var jasmineEnv = jasmine.getEnv();
            jasmineEnv.updateInterval = 1000;

            var teamCityReporter = new jasmine.TeamcityReporter();

            jasmineEnv.addReporter(teamCityReporter);
            var currentWindowOnload = window.onload;

            window.onload = function () {
                if (currentWindowOnload) {
                    currentWindowOnload();
                }
                execJasmine();
            };

            function execJasmine() {
                jasmineEnv.execute();
            }

        })();
    &#60;/script&#62;

&#60;/head&#62;

&#60;body&#62;
&#60;/body&#62;
&#60;/html&#62;</pre>
<p>Secondly, we need a control file for phantom.js that will load our runner. Here&#8217;s one based on Dan&#8217;s example that will run our tests and pipe the console output:</p>
<pre>    console.log('Loading a web page');
    var page = new WebPage();
    var url = "http://localhost:8080/tests/teamcityrunner";
    phantom.viewportSize = {width: 800, height: 600};

    //This is required because PhantomJS sandboxes the website and it does not show up the console messages form that page by default
    page.onConsoleMessage = function (msg) { console.log(msg); };

    //Open the website
    page.open(url, function (status) {

        //Page is loaded!
        if (status !== 'success') {
            console.log('Unable to load the address!');
        } else {
            //Using a delay to make sure the JavaScript is executed in the browser
            window.setTimeout(function () {
                page.render("output.png");
                phantom.exit();
            }, 1000);
        }
    });</pre>
<div style="height:1.4em;visibility:hidden;">spc</div>
<p>I wrote a quick command line app that will do the rest for us. All we need to do is supply it with the location of the iisexpress executable, the test site root, port, location of phantomjs and the control js file. Just make sure that you provide an appropriate timeout in the control.js file so that your tests have time to run before phantom.js closes.</p>
<p>I&#8217;ve copied the code for the console app into a gist as it was too long to post here: <a href="https://gist.github.com/Roysvork/5274142" rel="nofollow">https://gist.github.com/Roysvork/5274142</a>, you just need to compile this and copy it to your build server.</p>
<div style="height:1.4em;visibility:hidden;">spc</div>
<p>Finally, here&#8217;s a snapshot of the resulting configuration in Team City:</p>
<p><a href="http://roysvork.files.wordpress.com/2013/03/phantomexpress.png"><img class="aligncenter size-full wp-image-473" alt="phantomexpress" src="http://roysvork.files.wordpress.com/2013/03/phantomexpress.png?w=497&#038;h=285" width="497" height="285" /></a></p>
<p>Now when we run our build, phantom express will fire up iis express, run our tests and voila!</p>
<p><a href="http://roysvork.files.wordpress.com/2013/03/testresults.png"><img class="aligncenter size-full wp-image-474" alt="testresults" src="http://roysvork.files.wordpress.com/2013/03/testresults.png?w=406&#038;h=130" width="406" height="130" /></a></p>
<p>Now you can utilise all the benefits of MVC (or any other aspect of .net) to include files and specs for your Javascript unit test suite and render your test runner. Not bad!</p>
<div style="height:1.4em;visibility:hidden;">spc</div>
<p><strong>Pete</strong></p>
<div style="height:1.4em;visibility:hidden;">spc</div>
<p>References:</p>
<ul>
<li><a href="http://www.jetbrains.com/teamcity/" rel="nofollow">http://www.jetbrains.com/teamcity/</a></li>
<li><span style="line-height:13px;"><a href="http://blog.virtew.com/2012/08/18/setup-teamcity-on-an-azure-virtual-machine-for-windows-8-metro-style-apps/" rel="nofollow">http://blog.virtew.com/2012/08/18/setup-teamcity-on-an-azure-virtual-machine-for-windows-8-metro-style-apps/</a><br />
</span></li>
<li><a href="http://blog.danmerino.com/continuos-integration-ci-for-javascript-jasmine-and-teamcity/" rel="nofollow">http://blog.danmerino.com/continuos-integration-ci-for-javascript-jasmine-and-teamcity/</a></li>
<li><a href="http://www.iis.net/learn/extensions/using-iis-express/running-iis-express-from-the-command-line" rel="nofollow">http://www.iis.net/learn/extensions/using-iis-express/running-iis-express-from-the-command-line</a></li>
<li><a href="https://gist.github.com/Roysvork/5274142" rel="nofollow">https://gist.github.com/Roysvork/5274142</a></li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Hardcore Test Driven Development]]></title>
<link>http://colearningbe.wordpress.com/2013/03/29/hardcore-test-driven-development/</link>
<pubDate>Fri, 29 Mar 2013 16:03:21 +0000</pubDate>
<dc:creator>Erik Talboom</dc:creator>
<guid>http://colearningbe.wordpress.com/2013/03/29/hardcore-test-driven-development/</guid>
<description><![CDATA[One of my favorite sessions in the coderetreat format is the &#8220;TDD as if you meant it&#8221; ka]]></description>
<content:encoded><![CDATA[One of my favorite sessions in the coderetreat format is the &#8220;TDD as if you meant it&#8221; ka]]></content:encoded>
</item>
<item>
<title><![CDATA[javax.persistence.TransactionRequiredException (using Arquillian)]]></title>
<link>http://dwuysan.wordpress.com/2013/03/29/javax-persistence-transactionrequiredexception-using-arquillian/</link>
<pubDate>Fri, 29 Mar 2013 04:43:46 +0000</pubDate>
<dc:creator>dwuysan</dc:creator>
<guid>http://dwuysan.wordpress.com/2013/03/29/javax-persistence-transactionrequiredexception-using-arquillian/</guid>
<description><![CDATA[I recently encountered javax.persistence.TransactionRequiredException when I am trying to perform so]]></description>
<content:encoded><![CDATA[<p>I recently encountered <code>javax.persistence.TransactionRequiredException</code> when I am trying to perform some cleanup, on <code>@After</code> method in my unit test. I am currently playing with Arquillian (and it is such a great technology to complement Java EE).</p>
<p>The scenario is simple.</p>
<p>I have an <code>Item</code> entity, and I have <code>ItemService</code>. The service provides functionality to add an item and to retrieve it. That&#8217;s about it.</p>
<p>In unit test, for one reason or another, one might decide to <i>clean up</i>, or <code>DELETE</code> some item. However, in this case, I would very much like to keep my service layer clean, i.e. just because I happen to need a clean up on the test-side, I should not force my service to implement it. Perhaps another way to look at it is that this is my way to reduce coupling. The user of the service should knows about the service, and the service should not know about where it is being used. One direction, so to speak.</p>
<p>So, to start with, here&#8217;s the code:</p>
<p><strong>ItemDistributionServiceTest</strong></p>
<pre class="brush: java; title: ; wrap-lines: false; notranslate" title="">
package com.dwuysan.service;

import com.dwuysan.entity.Item;
import com.dwuysan.util.EntityManagerProducer;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author denywuy
 */
@RunWith(Arquillian.class)
public class ItemDistributionServiceTest {

    private Item item;
    @Inject
    private ItemService itemService;
    @Inject
    private EntityManager em;

    @Deployment
    public static JavaArchive createTestArchive() {
        return ShrinkWrap.create(JavaArchive.class)
                .addClass(Item.class)
                .addClass(ItemService.class)
                .addClass(EntityManagerProducer.class)
                .addAsManifestResource(&#34;test-persistence.xml&#34;, ArchivePaths.create(&#34;persistence.xml&#34;))
                .addAsManifestResource(&#34;META-INF/beans.xml&#34;, ArchivePaths.create(&#34;beans.xml&#34;))
                .addAsResource(&#34;ValidationMessages.properties&#34;);
    }

    @Before
    public void setup() {
        this.item = new Item();
        item.setCode(&#34;item01&#34;);
        item.setName(&#34;item01&#34;);
        item.setUom(&#34;piece&#34;);

        this.item = this.itemService.getItem(this.itemService.createItem(item));
    }

    @After
    public void cleanUp() throws Exception {
        this.em.remove(em.merge(this.item));
    }

    @Test
    public void testDistribute() throws Exception {
        /*
         * Test omitted
         */
    }
}
</pre>
<p>So, to <code>DELETE</code> the item, I directly use <code>EntityManager#remove(...)</code>. However, that results in the following error:</p>
<pre class="brush: bash; title: ; notranslate" title="">
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 11.847 sec &#60;&#60;&#60; FAILURE!
testDistribute(com.dwuysan.service.ItemDistributionServiceTest)  Time elapsed: 0.625 sec  &#60;&#60;&#60; ERROR!
javax.persistence.TransactionRequiredException
	at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:163)
	at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:145)
	at com.sun.enterprise.container.common.impl.EntityManagerWrapper.merge(EntityManagerWrapper.java:280)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
</pre>
<p> same as above</p>
<p>After further reading, I found that we need to explicitly initiates transaction. So, the code change slightly to:</p>
<p><strong>ItemDistributionServiceTest</strong></p>
<pre class="brush: java; title: ; wrap-lines: false; notranslate" title="">
package com.dwuysan.service;

// the rest of the imports go here
import javax.annotation.Resource;
import javax.transaction.UserTransaction;

@RunWith(Arquillian.class)
public class ItemDistributionServiceTest {

    private Item item;

    // the rest of the injections go here
    @Resource
    private UserTransaction utx;

    @Deployment
    public static JavaArchive createTestArchive() {
        // same as above
    }

    @Before
    public void setup() {
        // same as above
    }

    @After
    public void cleanUp() throws Exception {
        utx.begin();
        this.em.remove(em.merge(this.item));
        utx.commit();
    }

    @Test
    public void testDistribute() throws Exception {
        /*
         * Test omitted
         */
    }
}
</pre>
<p><strong>Reference:</strong></p>
<p>Kosi2801, 2009, <a target="_blank" href="http://stackoverflow.com/questions/1084627/entitymanager-throws-transactionrequiredexception-on-merge-in-jboss-jsf-bean">EntityManager throws TransactionRequiredException on merge() in JBoss JSF bean</a>, accessed 29 March 2013.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[New SharePoint Features for Developers]]></title>
<link>http://jfattic.wordpress.com/2013/03/27/new-sharepoint-features-for-developers/</link>
<pubDate>Wed, 27 Mar 2013 20:33:28 +0000</pubDate>
<dc:creator>jfattic</dc:creator>
<guid>http://jfattic.wordpress.com/2013/03/27/new-sharepoint-features-for-developers/</guid>
<description><![CDATA[I recently completed a tour through Kansas City, Minneapolis, Des Moines, and Omaha to demonstrate t]]></description>
<content:encoded><![CDATA[<p>I recently completed a tour through Kansas City, Minneapolis, Des Moines, and Omaha to demonstrate the new capabilities for SharePoint developers available in Visual Studio Update 1. (Thanks to all of you that attended – despite this crazy weather!)</p>
<table width="400" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td align="center" valign="top" width="400">A special thanks to Neil Iversen from Avtex for his presentation and demos on the new features in SharePoint 2013. His passion and knowledge on the topic was most evident.</td>
</tr>
</tbody>
</table>
<p><a href="http://jfattic.files.wordpress.com/2013/03/image3.png"><img style="background-image:none;padding-top:0;padding-left:0;margin:0;display:inline;padding-right:0;border:0;" title="image" alt="image" src="http://jfattic.files.wordpress.com/2013/03/image_thumb3.png?w=244&#038;h=111" width="244" height="111" border="0" /></a></p>
<p>Three key features for SharePoint developers were the focus of my session:</p>
<h1>Unit testing SharePoint</h1>
<p><span style="font-size:medium;"><img class="wlEmoticon wlEmoticon-sadsmile" style="border-style:none;" alt="Sad smile" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-sadsmile.png" /></span>Most SharePoint developers I know don’t write unit tests. It’s just too hard to isolate your custom logic from SharePoint. Without unit tests, developers must spend a lot of time setting up environments, inserting test data, and walking through numerous pages to see if their code is working as intended.</p>
<p><img class="wlEmoticon wlEmoticon-rollingonthefloorlaughing" style="border-style:none;" alt="Rolling on the floor laughing" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-rollingonthefloorlaughing.png" />Visual Studio 2012 Update 1 adds a SharePoint emulation capability based on the Fakes Framework. You can now write unit tests against your code without even having a live instance of SharePoint! You can even alter the behavior of the SharePoint API to control what the API returns to you.</p>
<p>This feature requires <a href="http://www.microsoftstore.com/store/msstore/list/categoryID.50804700?WT.mc_id=pointitsem_US_Bing_5-VisualStudio_buy&#38;wt.term=buy%20microsoft%20visual%20studio&#38;wt.campaign=5+-+Visual+Studio&#38;wt.content=XFOTcXpZ&#38;wt.source=bing&#38;wt.medium=cpc&#38;WT.srch=1" target="_blank">Visual Studio Premium</a> and <a href="http://www.microsoft.com/visualstudio/eng/visual-studio-update#story-update-1" target="_blank">Update 1</a>.</p>
<h1>Performance and load testing SharePoint</h1>
<p><img class="wlEmoticon wlEmoticon-steamingmad" style="border-style:none;" alt="Steaming mad" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-steamingmad.png" />Any time you are writing code, its always good to keep in mind performance implications. Users get frustrated when applications aren’t responsive. Unfortunately, SharePoint is such a dynamic system, that it could be hard to create usable web performance tests in earlier versions of Visual Studio. With sites, lists, and documents all having unique identifiers that varied across environments, these tests would require a lot of manual revisions to the recorded URL’s. There was also a lot of extra “noise” in the HTTP traffic.</p>
<p><img class="wlEmoticon wlEmoticon-fingerscrossed" style="border-style:none;" alt="Fingers crossed" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-fingerscrossed.png" />It never fails that when users need something in SharePoint, a LOT of them also need it – at the same time. So, load testing is also important in SharePoint. They’ll sometimes make a problem worse by retrying their last action because they aren’t sure its working properly.</p>
<p><img class="wlEmoticon wlEmoticon-hotsmile" style="border-style:none;" alt="Hot smile" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-hotsmile.png" />Update 1 adds features to make the recording of web performance tests ignore the noise and identify any SharePoint error pages encountered. The dynamic parameter detection has been extended to extract and pass the unique identifiers for SharePoint objects like site names, list GUIDs, document names, and more.</p>
<p>This feature requires <a href="http://www.microsoftstore.com/store/msstore/list/categoryID.50804700?WT.mc_id=pointitsem_US_Bing_5-VisualStudio_buy&#38;wt.term=buy%20microsoft%20visual%20studio&#38;wt.campaign=5+-+Visual+Studio&#38;wt.content=XFOTcXpZ&#38;wt.source=bing&#38;wt.medium=cpc&#38;WT.srch=1" target="_blank">Visual Studio Ultimate</a> and <a href="http://www.microsoft.com/visualstudio/eng/visual-studio-update#story-update-1" target="_blank">Update 1</a>.</p>
<h1>Advanced debugging SharePoint with IntelliTrace</h1>
<p><img class="wlEmoticon wlEmoticon-surprisedsmile" style="border-style:none;" alt="Surprised smile" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-surprisedsmile.png" />Do you support issues reported by your SharePoint users? Ever wonder what to do with those correlation IDs you see on a SharePoint error page? Its not always easy to reproduce issues within SharePoint.</p>
<p><img class="wlEmoticon wlEmoticon-redheart" style="border-style:none;" alt="Red heart" src="http://jfattic.files.wordpress.com/2013/03/wlemoticon-redheart.png" />This update makes it very easy to take advantage of IntelliTrace in order to see what lines of your code executed leading up to the reported issue. Even though the error didn’t occur in your development environment, IntelliTrace will log all of the activity so you can play it back in Visual Studio – even if you don’t have the source code on your machine! You can also filter to specific correlation IDs within the IntelliTrace log.</p>
<p>This feature requires <a href="http://www.microsoftstore.com/store/msstore/list/categoryID.50804700?WT.mc_id=pointitsem_US_Bing_5-VisualStudio_buy&#38;wt.term=buy%20microsoft%20visual%20studio&#38;wt.campaign=5+-+Visual+Studio&#38;wt.content=XFOTcXpZ&#38;wt.source=bing&#38;wt.medium=cpc&#38;WT.srch=1" target="_blank">Visual Studio Ultimate</a> and <a href="http://www.microsoft.com/visualstudio/eng/visual-studio-update#story-update-1" target="_blank">Update 1</a>.</p>
<p>You can download the slides for our sessions from my SkyDrive <a href="https://skydrive.live.com/redir?resid=E203D9933DCEBCA1!173" target="_blank">here</a>. Most of my demo’s were based on the hands-on labs <a href="http://download.microsoft.com/download/A/9/2/A9253B14-5F23-4BC8-9C7E-F5199DB5F831/Testing%20and%20Debugging%20SharePoint%202010%20Applications%20with%20Visual%20Studio%202012.docx" target="_blank">here</a> (and get the associated VM <a href="http://blogs.msdn.com/b/briankel/archive/2011/09/16/visual-studio-11-application-lifecycle-management-virtual-machine-and-hands-on-labs-demo-scripts.aspx" target="_blank">here</a>).</p>
<p>Are you a SharePoint developer? Are these new features interesting to you? Let me know what you think.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Asserting lambda expressions being passed to methods are correct]]></title>
<link>http://techblog.moneyvista.com/2013/03/27/asserting-lambda-expressions-being-passed-to-methods-are-correct/</link>
<pubDate>Wed, 27 Mar 2013 15:44:00 +0000</pubDate>
<dc:creator>godders83</dc:creator>
<guid>http://techblog.moneyvista.com/2013/03/27/asserting-lambda-expressions-being-passed-to-methods-are-correct/</guid>
<description><![CDATA[A simple post to get the MoneyVista tech blog properly up and running. I was recently TDD&#8217;ing]]></description>
<content:encoded><![CDATA[<p>A simple post to get the MoneyVista tech blog properly up and running.</p>
<p>I was recently TDD&#8217;ing some new code here at MoneyVista and wanted to assert that the expression passed to an IRepository method was correct.  This was a key test as changing the expression in the future would fundamentally change the behaviour of the SUT.  Other than the normal benefits of TDD I wanted to ensure that anyone changing the expression in the future would have to do so with good reason, as they would also then need to fix a failing unit test.</p>
<p>I&#8217;ve FooBar&#8217;d the classes of interest from the MoneyVista code base &#8211; so I hope it still makes sense.</p>
<p>First up we have our IRepository which just exposes a FindAll&#60;T&#62; method.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
public interface IRepository
{
  IQueryable&#60;T&#62; FindAll&#60;T&#62;(Expression&#60;Func&#60;T, bool&#62;&#62; expression ) where T : IDomainObject;
}
</pre>
<p>Next we have a Queue obejct whose responsibility is to find all BarFoo objects with a status of New, map to FooBar objects and return. The Queue uses an instance of IRepository and IMapper (which is a simple wrapper around the normally static AutoMapper so that I can inject it as a dependency to the Queue).</p>
<pre class="brush: csharp; title: ; notranslate" title="">
public class Queue
{
  /*
  fields and ctor()
  */

  public IEnumerable&#60;FooBar&#62; GetNewFooBars()
  {
    var fooBars = new List&#60;FooBar&#62;();

    foreach (var barFoo in _repository.FindAll&#60;BarFoo&#62;(x =&#62; x.Status == BarFooStatus.New))
    {
      fooBars.Add(_mapper.Map&#60;BarFoo, FooBar&#62;(barFoo));
    }

    return fooBars;
  }
}
</pre>
<p>Using Moq we can test that the expression &#8220;x =&#62; x.Status == BarFooStatus.New&#8221; is passed to IRepository as follows.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[TestClass]
public class QueueTests
{
  private Mock&#60;IRepository&#62; _repository;
  private Mock&#60;IMapper&#62; _mapper;
  private Queue _queue;

  [TestInitialize]
  public void TestInitialize()
  {
    _repository = new Mock&#60;IRepository&#62;();
    _mapper = new Mock&#60;IMapper&#62;();
    _queue = new Queue(_repository.Object, _mapper.Object);
  }

  [TestMethod]
  public void GetNewFooBars_FindsNewBarFoosOnly()
  {
    // Arrange
    Expression&#60;Func&#60;BarFoo, bool&#62;&#62; expectedExpression = x =&#62; x.Status == BarFooStatus.New;
    Expression&#60;Func&#60;BarFoo, bool&#62;&#62; actualExpression = null;

    _repository.Setup(x =&#62; x.FindAll(It.IsAny&#60;Expression&#60;Func&#60;BarFoo, bool&#62;&#62;&#62;()))
      .Callback((Expression&#60;Func&#60;BarFoo, bool&#62;&#62; x) =&#62; actualExpression = x)
      .Returns(new List&#60;BarFoo&#62;().AsQueryable());

    // Act
    _queue.GetNewFooBars();

    // Assert
    Assert.AreEqual(expectedExpression.ToString(), actualExpression.ToString());
  }
 }
</pre>
<p>Using Moq&#8217;s Callback method to store the actual expresion passed to the mock works great &#8211; the only caveat to mention is that the assert is based on the string representation of the expressions, so if Queue changed to &#8220;y =&#62; y.Status == BarFooStatus.New&#8221; the test would fail. This is something that I can live with in order to get the testing benefit.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Easy4PHPUnit: Easy 4 Steps PHP Unit Testing Framework]]></title>
<link>http://webinstitute.wordpress.com/2013/03/25/easy4phpunit-easy-4-steps-php-unit-testing-framework/</link>
<pubDate>Tue, 26 Mar 2013 04:45:13 +0000</pubDate>
<dc:creator>3D Immortal</dc:creator>
<guid>http://webinstitute.wordpress.com/2013/03/25/easy4phpunit-easy-4-steps-php-unit-testing-framework/</guid>
<description><![CDATA[I&#8217;m fascinated a lot by the power and confidence that unit testing gives to the software devel]]></description>
<content:encoded><![CDATA[I&#8217;m fascinated a lot by the power and confidence that unit testing gives to the software devel]]></content:encoded>
</item>
<item>
<title><![CDATA[The Benefits of Unit Testing]]></title>
<link>http://jakeradakovich.com/2013/03/24/the-benefits-of-unit-testing/</link>
<pubDate>Sun, 24 Mar 2013 18:23:24 +0000</pubDate>
<dc:creator>Jake Radakovich</dc:creator>
<guid>http://jakeradakovich.com/2013/03/24/the-benefits-of-unit-testing/</guid>
<description><![CDATA[When I interviewed for my first job out of college, one of the questions that the interviewer asked]]></description>
<content:encoded><![CDATA[<p>When I interviewed for my first job out of college, one of the questions that the interviewer asked was &#8220;what do you know about unit testing?&#8221;  Of course, I was nervous, and I wanted the job.  It&#8217;s really hard to admit that you don&#8217;t know something, especially something as ubiquitous as unit testing.  Unit testing wasn&#8217;t taught in my college computer science department.  The only exposure to unit testing I had in college was from various blogs and tutorials that I read outside of class.  I admitted, albeit reluctantly, that I didn&#8217;t know very much about unit testing.  He replied, &#8220;Here&#8217;s a tip, learn about unit testing.&#8221;</p>
<p>I got the job despite my lack of unit testing knowledge. The initial several months of my development career involved fixing bugs in legacy code.  There were no unit tests, the code was heavily coupled, and it was just really, really hard to maintain.  With my head deep in legacy code, I still didn&#8217;t have much exposure to unit testing.  We eventually decided to refactor as much of the code as possible, and this is where I really progressed in my knowledge of unit testing.</p>
<p>In the following several years, I have come to realize the practical benefits of unit testing.  I strive to make sure developers on my project check in code that has close to 100% test coverage, and that they understand the utility of this practice.   I have noticed that many developers fail to realize the benefits of writing tests, regardless of their experience.</p>
<p>This will be a multi-part series on unit testing, and I will give examples of how and why to unit test.  The examples will be written in Java using <a title="JUnit" href="http://junit.org/" target="_blank">JUnit</a> and <a title="EasyMock" href="http://www.easymock.org/" target="_blank">Easymock</a>, but I think that the essence of the posts will be applicable to any application and programming language.</p>
<p>I am by no means the authority on unit testing, so if you have anything to add, I would love for you to comment on the posts.  The only thing I ask is that it not devolve into pedantry.</p>
<p><a href="http://jakeradakovich.wordpress.com/2013/03/30/the-benefits-of-unit-testing-pt-1-isolation/" title="isolation">Part 1 &#8211; Isolates Development</a><br />
<a href="http://jakeradakovich.wordpress.com/2013/04/06/the-benefits-of-unit-testing-pt-2-encouraging-analysis/" title="Encourages Analysis">Part 2 &#8211; Encourages Analysis</a><br />
<a href="http://jakeradakovich.wordpress.com/2013/04/11/the-benefits-of-unit-testing-pt-3-facilitates-refactoring/" title="Facilitates Refactoring">Part 3 &#8211; Facilitates Refactoring</a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Rolling rolling rolling - rolling back your data back in integration tests]]></title>
<link>http://handmadecode.com/2013/03/22/rollin-rollin-rollin-rollin-back-your-data-back-in-integration-tests/</link>
<pubDate>Fri, 22 Mar 2013 13:13:56 +0000</pubDate>
<dc:creator>Jim</dc:creator>
<guid>http://handmadecode.com/2013/03/22/rollin-rollin-rollin-rollin-back-your-data-back-in-integration-tests/</guid>
<description><![CDATA[A couple years ago, I had just started refactoring a legacy codebase by adding integration tests and]]></description>
<content:encoded><![CDATA[<p>A couple years ago, I had just started refactoring a legacy codebase by adding integration tests and was manually rolling back the database changes with several lines of handwritten sql deletes… (sorry). At Iowa Code Camp, I went to a Lee Brandt demo and looking at Lee’s demo code, I saw him using a transaction for the rollbacks and I hung my head in shame.</p>
<p>Try it like this:</p>
<pre class="brush: css; title: ; notranslate" title="">
using NUnit.Framework;
using System.Transactions;
namespace ProjectName.Tests.Integration
{
 [TestFixture]
 public class TestClass
 {
 private TransactionScope _transactionScope;
 [SetUp]
 public void SetUp()
 {
 _transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew);
 }
 //...Test some stuff, insert records, update records, etc...
 [TearDown]
 public void TearDown()
 {
 _transactionScope.Dispose();
 }
 }
}

</pre>
<p>Happy Testing,</p>
<p>Jim</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[My Simple View of Testing for Software Developers]]></title>
<link>http://thewonggei.wordpress.com/2013/03/20/my-simple-view-of-testing-for-software-developers/</link>
<pubDate>Wed, 20 Mar 2013 20:06:34 +0000</pubDate>
<dc:creator>thewonggei</dc:creator>
<guid>http://thewonggei.wordpress.com/2013/03/20/my-simple-view-of-testing-for-software-developers/</guid>
<description><![CDATA[Assumptions + important edge cases. That&#8217;s it. That&#8217;s all I consider when I&#8217;m test]]></description>
<content:encoded><![CDATA[Assumptions + important edge cases. That&#8217;s it. That&#8217;s all I consider when I&#8217;m test]]></content:encoded>
</item>
<item>
<title><![CDATA[What is Service Virtualization?]]></title>
<link>http://mkaufman.wordpress.com/2013/03/20/what-is-service-virtualization/</link>
<pubDate>Wed, 20 Mar 2013 14:58:41 +0000</pubDate>
<dc:creator>mkaufman</dc:creator>
<guid>http://mkaufman.wordpress.com/2013/03/20/what-is-service-virtualization/</guid>
<description><![CDATA[There has been a lot of discussion lately about &#8220;service virtualization&#8221;, however the te]]></description>
<content:encoded><![CDATA[<p>There has been a lot of discussion lately about &#8220;service virtualization&#8221;, however the term alone can make your head spin. Are we talking about server virtualization? What types of services are involved? What does virtualization have to do with testing? I&#8217;d like to quickly clear up any confusion you may have. Service virtualization is used to simulate the behavior of components in an application so you can perform an accurate and timely test in a world of complex interrelated applications. Production services that may not be available for integration testing can be virtualized so the testing can take place at an appropriate time in the software development process.</p>
<p>While quality professionals have always needed to test combinations of code, current methods for writing and combining code have changed so much that traditional approaches to testing can’t get the job done at the right price and the right time.  There is a fast growing commercial market for production services that are incorporated as self-contained modules into software applications. Third party services such as PayPal or a credit checking service are increasingly used in customer facing applications.</p>
<p>Use of these third-party services increases the efficiency of software development, but at the same time makes your application dependent on services that you do not control. Consider, for example, the scenario of an online retailer with multiple suppliers. The retailer has created a new mobile application for customers.  This application uses a credit check service provided by a third-party vendor. The team can’t test without this dependent component, but it is not available for testing. Without service virtualization, the software development team has some difficult choices to make and none of the options are good. If the development team proceeds without doing the necessary testing, they may introduce errors that are much harder and more costly to fix later on. If the team waits until the third-party service is available, developer productivity will decline and the team may miss production deadlines. In addition, if the third-party service becomes available it can get pretty expensive to test application performance at high usage levels since the service costs money each time it is executed.</p>
<p>So what does the development team do in this situation? Service virtualization is a new approach to testing that helps organizations eliminate some of the testing bottlenecks that make it hard to bring new high quality applications to market quickly. Here are five key things you should know about service virtualization.</p>
<ol>
<li>To get started with service virtualization you need to understand your testing methodology and think about where service virtualization can increase team velocity while also helping your team to deliver higher quality software.</li>
<li>Use a cost/benefit analysis to select which services should be virtualized.  Consider the cost to your company when testing is delayed because dependent services or software are not available for testing. How much is spent on staff needed to set up and maintain test environments? How much do you spend to maintain test environments that are not fully utilized? What is the cost for software licenses in the physical test lab environment? What is the cost of third-party service access fees?</li>
<li>Service virtualization can help you find errors in all testing phases- including unit testing, performance testing, integration testing, system testing, system integration testing, user acceptance testing, and operability testing.</li>
<li>Recording a service that already exists is a great way to define the behavior of your virtual component. You can use the recording process to identify the behaviors that will need to be simulated so you can create test cases quickly.</li>
<li>You can’t expect to virtualize all your components. Therefore, you need to be able to easily move back and forth between real components and virtual components while you are testing. You want to maintain consistency across real and virtual components.</li>
</ol>
<p>One of the biggest impacts of service virtualization for developers is the ability to validate integrations much earlier in the application life cycle. The software development team can move beyond unit testing and overcome many of the roadblocks that inhibit timely, efficient, and cost effective testing.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Fixing pip and easy_install, and getting colorful output from unittest]]></title>
<link>http://darknightelf.wordpress.com/2013/03/19/fixing-pip-and-easy_install-and-getting-colorful-output-from-unittest/</link>
<pubDate>Wed, 20 Mar 2013 00:05:33 +0000</pubDate>
<dc:creator>darknightelf</dc:creator>
<guid>http://darknightelf.wordpress.com/2013/03/19/fixing-pip-and-easy_install-and-getting-colorful-output-from-unittest/</guid>
<description><![CDATA[I&#8217;ve noticed in a lot of talks/ videos that people in the Ruby universe that work with tools l]]></description>
<content:encoded><![CDATA[<p>I&#8217;ve noticed in a lot of talks/ videos that people in the Ruby universe that work with tools like RSpec for writing unit tests/ doing TDD often have a nice colorful output. Aesthetics aside, I like the idea of the visual feedback &#8211; with <span style="color:#ff0000;">red</span> indicating your errors or failures and <span style="color:#00ff00;">green</span> or <span style="color:#3366ff;">blue</span> indicating your passing tests. It makes it much easier to use the sense of color to get feedback instead of having to actually carefully read the text scrolling on the terminal. There has to be a reason, after all, why TDD often has the moniker red-green-refactor. Searching on this matter, I rather quickly came across <a title="pyrg" href="https://pypi.python.org/pypi/pyrg" target="_blank">pyrg</a>, which seems like an excelled tool.</p>
<p>However, since I kind of overwrote my existing Python installation (OS X 10.6) with the version from Macports, my <em>easy_install</em> and <em>pip</em> were still pointing toward one of my older Python installations. Ergo, <em>pyrg</em> wouldn&#8217;t run. After researching for a while I came across <a title="Mac easy_install" href="http://stackoverflow.com/questions/6012246/why-is-python-easy-install-not-working-on-my-mac" target="_blank">this excellent post on Stack Overflow</a>, and followed the instructions to uninstall my <em>easy_install</em> and then reinstall using the <em>distribute</em> package mentioned on there, followed by reinstalling <em>pip</em>.</p>
<p>This by itself didn&#8217;t do anything, and I had to make sure in my shell&#8217;s rc file that the Macport version of Python was in the path before other, regular places like <em>/usr/local/bin</em>, etc. That fixed it. Run with <em>$ pyrg python_file</em> or<em> $ python python_file &#124;&#38; pyrg</em>. Colors can be easily customized as well. Hooray for going from the colorless test run output on the left to a proper visual feedback on the right!</p>
<div id="attachment_340" class="wp-caption alignright" style="width: 190px"><a href="http://darknightelf.files.wordpress.com/2013/03/colorful.png" target="_blank"><img class=" wp-image-340   " title="With pyrg" alt="Colorful" src="http://darknightelf.files.wordpress.com/2013/03/colorful.png?w=180&#038;h=172" width="180" height="172" /></a><p class="wp-caption-text">Colorful with pyrg</p></div>
<div id="attachment_341" class="wp-caption alignleft" style="width: 190px"><a href="http://darknightelf.files.wordpress.com/2013/03/colorless.png" target="_blank"><img class=" wp-image-341  " title="Without pyrg" alt="Colorless" src="http://darknightelf.files.wordpress.com/2013/03/colorless.png?w=180&#038;h=173" width="180" height="173" /></a><p class="wp-caption-text">Colorless without pyrg</p></div>
]]></content:encoded>
</item>
<item>
<title><![CDATA[My first time doing unit testing by NUnit]]></title>
<link>http://indoexpatriate.wordpress.com/2013/03/18/my-first-time-doing-unit-testing-by-nunit/</link>
<pubDate>Mon, 18 Mar 2013 12:38:52 +0000</pubDate>
<dc:creator>edwin2026</dc:creator>
<guid>http://indoexpatriate.wordpress.com/2013/03/18/my-first-time-doing-unit-testing-by-nunit/</guid>
<description><![CDATA[Around 2 days ago, I have just tried to use NUnit. NUnit is software used to do unit testing during]]></description>
<content:encoded><![CDATA[<p>Around 2 days ago, I have just tried to use NUnit. NUnit is software used to do unit testing during software development in C# ASP.NET environment. At first, it took quite a while (around 1-2 hours) just to figure out, install and learn how to use this software.</p>
<p>This is my first time using unit testing tool because in my previous job, a lack of documentation on system workflow always prevented me to create well defined test cases and its expected results. Here, the new developer has done excellent job on documenting the workflow and made my job is easier (I am using version 2.6.1 on Visual Studio 2010 on Windows 8, btw).</p>
<p>And then come first obstacle after installation. I encountered error alert box popped up when I try to load my DLL project file into newly created NUnit project. The error said: &#8220;<strong>This assembly was not build by any known testing framework</strong>&#8220;. After minutes of browsing on stackoverflow and couples of forum, it turned out that I need to go to the Tools -&#62; Settings -&#62; IDE Support -&#62; Visual Studio and check the option: &#8220;Enable Visual Studio support&#8221; as indicated in figure below:</p>
<p><a href="http://indoexpatriate.files.wordpress.com/2013/03/nunit-enable-visual-studio-support.png"><img class="alignnone size-large wp-image-783" alt="NUnit - Enable Visual Studio support" src="http://indoexpatriate.files.wordpress.com/2013/03/nunit-enable-visual-studio-support.png?w=640&#038;h=425" width="640" height="425" /></a></p>
<p>After that, you can load the DLL file to NUnit project. However, at this moment, I confused because it turned out the graphical appearance for my project is quite different from the sample project in the bundled NUnit software. The sample project has a look of apparently some classes together with its methods and a set of test cases to be executed upon clicking &#8216;Run&#8217; button at the main interface:</p>
<p><a href="http://indoexpatriate.files.wordpress.com/2013/03/nunit-sample-project.png"><img class="alignnone size-large wp-image-786" alt="NUnit - Sample Project" src="http://indoexpatriate.files.wordpress.com/2013/03/nunit-sample-project.png?w=640&#038;h=489" width="640" height="489" /></a></p>
<p>In contrast, my DLL project did not have tick and cross icons and no public methods which were defined inside those DLL project were visible from this NUnit GUI screen. It turned out that we need to incorporate NUnit library (nunit.framework.dll) located inside bin folder of NUnit program into our Visual Studio project. You can right click and choose &#8216;Add reference&#8230;&#8217; in Solution Explorer window and browse that DLL file inside NUnit installation path.</p>
<p>After that you can test your methods which are contained inside code behind file. First, just add NUnit.Framework namespace and then use [TestCase] statement above the methods which you want to test as shown below:</p>
<p><a href="http://indoexpatriate.files.wordpress.com/2013/03/nunit-inside-c-code.png"><img class="alignnone size-large wp-image-778" alt="NUnit inside C# code" src="http://indoexpatriate.files.wordpress.com/2013/03/nunit-inside-c-code.png?w=640&#038;h=360" width="640" height="360" /></a></p>
<p>After that, I compiled my class library project and then I reopened the NUnit project and viola, the test is working now:</p>
<p><a href="http://indoexpatriate.files.wordpress.com/2013/03/nunit-testing1.png"><img class="alignnone size-large wp-image-777" alt="NUnit testing" src="http://indoexpatriate.files.wordpress.com/2013/03/nunit-testing1.png?w=640&#038;h=346" width="640" height="346" /></a></p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Kiwi's Basic Unit Testing]]></title>
<link>http://codeplease.wordpress.com/2013/03/16/kiwis-basic-unit-testing/</link>
<pubDate>Sat, 16 Mar 2013 19:47:06 +0000</pubDate>
<dc:creator>Rui Peres</dc:creator>
<guid>http://codeplease.wordpress.com/2013/03/16/kiwis-basic-unit-testing/</guid>
<description><![CDATA[If you want to make just some basic tests, with Kiwi, in your UIViewController&#8216;s IBOutlets and]]></description>
<content:encoded><![CDATA[<p>If you want to make just some basic tests, <a href="https://github.com/allending/Kiwi" target="_blank">with Kiwi</a>, in your <code>UIViewController</code>&#8216;s <code>IBOutlets</code> and <code>IBActions</code>, you can do something like this:</p>
<pre class="brush: objc; title: ; notranslate" title="">
 __block MyViewController *viewController = nil;
                
 beforeAll(^{ // Occurs once
 });
                
 afterAll(^{ // Occurs once
 });
                
 beforeEach(^{
   viewController = [[MyViewController alloc] initWithNibName:@&#34;MyViewController&#34; bundle:nil];
   // Lazy loading of the UIView's
   __unused UIView *aView = viewController.view;
 });
                
 afterEach(^{
   viewController = nil;
 });
                
 it(@&#34;should not be nil&#34;, ^{
   [viewController shouldNotBeNil];
 });
                
 it(@&#34;should have the IBOutlets not nilled&#34;, ^{                            
   // The description's Label IBOutlet
   UILabel *descriptionLabel = (UILabel *)[viewController objectForPropertyName:@&#34;descriptionLabel&#34;];
   [descriptionLabel shouldNotBeNil];
 });

 it(@&#34;should respond to the IBActions&#34;, ^{
   // This Button should have an action
   NSNumber *actionMethod = @([viewController respondsToSelector:@selector(anAction:)]);
   [[actionMethod should] beTrue];
 });
</pre>
<p>Don&#8217;t forget that with this you are only able to see that the <code>IBAction</code> exist and the <code>UIViewController</code> responds to it&#8230; <strong>Not that the your Xib&#8217;s element is connect to it</strong>.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Test base class thanks to Rob Connery]]></title>
<link>http://handmadecode.com/2013/03/13/test-base-class-thanks-to-rob-connery/</link>
<pubDate>Wed, 13 Mar 2013 12:38:59 +0000</pubDate>
<dc:creator>Jim</dc:creator>
<guid>http://handmadecode.com/2013/03/13/test-base-class-thanks-to-rob-connery/</guid>
<description><![CDATA[I saw this great testbase class in a Tekpub video. Thank goodness for tekpub videos. I wish everythi]]></description>
<content:encoded><![CDATA[<p>I saw this great testbase class in a <a href="http://tekpub.com" target="_blank">Tekpub</a> video. Thank goodness for <a href="http://tekpub.com" target="_blank">tekpub</a> videos. I wish everything that I purchased was that pragmatic.</p>
<pre class="brush: css; title: ; notranslate" title="">
public class TestBase
{
	public static string GetCaller()
	{
		StackTrace stackTrace = new StackTrace();
		return stackTrace.GetFrame(2).GetMethod().Name;
	}

	public void IsPending()
	{
		Console.WriteLine(&#34;{0} -- pending&#34;, GetCaller());
	}

	public void Describes(string description)
	{
		Console.WriteLine(&#34;-----------------------&#34;);
		Console.WriteLine(description);
		Console.WriteLine(&#34;-----------------------&#34;);
	}
}
</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Lecture 2: Introduction to JUnit, JMock and Hamcrest]]></title>
<link>http://advancedsecourse.wordpress.com/2013/03/13/introduction-to-junit-jmock-and-hamcrest/</link>
<pubDate>Wed, 13 Mar 2013 10:58:05 +0000</pubDate>
<dc:creator>npetalid</dc:creator>
<guid>http://advancedsecourse.wordpress.com/2013/03/13/introduction-to-junit-jmock-and-hamcrest/</guid>
<description><![CDATA[Today&#8217;s lecture focuses on the tools we use to test software. We introduce testing (in its bro]]></description>
<content:encoded><![CDATA[<p>Today&#8217;s lecture focuses on the tools we use to test software. We introduce testing (in its broader sense), JUnit, JMock and Hamcrest.</p>
<p>These are not the only available tools but they are amongst the most popular.</p>
<p>You can find today&#8217;s slides <a title="Lecture 2 Slides" href="https://dl.dropbox.com/u/22231225/AdvancedSE/2Testing.pdf">here</a>.</p>
<p>You can find some example code <a title="Example Netbeans project" href="https://dl.dropbox.com/u/22231225/AdvancedSE/SimpleExample.zip">here</a></p>
<p>You should also check out papers on testing, JUnit and JMock such as</p>
<ul>
<li><a title="Mock Roles, Not Objects" href="http://jmock.org/oopsla2004.pdf" target="_blank">Steve Freeman, Nat Pryce, Tim Mackinnon, Joe Walnes, &#8220;Mock Roles, Not Objects&#8221;, OOPSLA 2004</a></li>
</ul>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Rhino Mocks Cheat Sheet]]></title>
<link>http://lukewickstead.wordpress.com/2013/03/10/rhino-mocks-cheat-sheet/</link>
<pubDate>Sun, 10 Mar 2013 16:22:30 +0000</pubDate>
<dc:creator>LW</dc:creator>
<guid>http://lukewickstead.wordpress.com/2013/03/10/rhino-mocks-cheat-sheet/</guid>
<description><![CDATA[A cheat sheet for Rhino Mocks v 3.6 in C# All source code can be found on GitHub here. This post is]]></description>
<content:encoded><![CDATA[<p>A cheat sheet for Rhino Mocks v 3.6 in C#</p>
<p>All source code can be found on GitHub <a href="https://github.com/lukewickstead/DOT-NET-on-Linux">here</a>.</p>
<p>This post is part of my <a title="Cheat Sheet Series" href="http://lukewickstead.wordpress.com/2013/01/13/cheat-sheet-series/">cheat sheet series</a>.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
// *** STUB ****
// A stub is an object which is required to pass the SUT.

mocks.CreateStub&#60;T&#62;(); 

// The simple stub
var sut = MockRepository.GenerateStub&#60;ISimpleModel&#62;();         
sut.Stub(x =&#62; x.Do()).Return(1);

// Stub Property
sut.Stub(x =&#62; x.AReadonlyPropery).Return(1); // Reaonly ( only get )
sut.AProperty = 2; // Stub Get

// Repeat
mock.Stub(x =&#62; x.Do()).Return(1).Repeat.Once();
mock.Stub(x =&#62; x.Do()).Return(2).Repeat.Twice();
mock.Stub(x =&#62; x.Do()).Return(3).Repeat.Times(3);

// Events
mock.Raise(x =&#62; x.Load += null, this, EventArgs.Empty);

// **** Arguments Conditional ****
// These can be used for Stub, Expect, AssertWasCalled and AssertWasNotCalled

// Ignore Arguments Conditional
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.Equal(1))).IgnoreArguments().Return(1);

// Is Conditionals
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.Anything)).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.Equal(1))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.NotEqual(1))).Return(10);       
sut.Stub(x =&#62; x.DoIFoo(Arg&#60;Foo&#62;.Is.Null)).Return(1);
sut.Stub(x =&#62; x.DoIFoo(Arg&#60;Foo&#62;.Is.NotNull)).Return(2);
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.LessThanOrEqual(10))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.GreaterThan(10))).Return(2);
sut.Stub(x =&#62; x.DoIFoo(Arg&#60;Foo&#62;.Is.Same(foo))).Return(1);
sut.Stub(x =&#62; x.DoIFoo(Arg&#60;Foo&#62;.Is.NotSame(foo))).Return(2);
sut.Stub(x =&#62; x.DoIFoo(Arg&#60;Foo&#62;.Is.TypeOf)).Return(1);      

// Matches Conditional
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Matches(y =&#62; y &#62; 5))).Return(1);

// List Conditionals
sut.Stub(x =&#62; x.Do(Arg&#60;List&#60;int&#62;&#62;.List.Count(RIS.Equal(0)))).Return(0);
sut.Stub(x =&#62; x.Do(Arg&#60;List&#60;int&#62;&#62;.List.Element(0, RIS.Equal(1)))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#60;List&#60;int&#62;&#62;.List.Equal(new int[] { 4, 5, 6 }))).Return(2);
sut.Stub(x =&#62; x.Do(Arg&#60;List&#60;int&#62;&#62;.List.IsIn(1))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.List.OneOf(new int[] { 4, 5, 6 }))).Return(2);   

// ByRef and Out parameters 
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.Equal(1), ref Arg&#60;int&#62;.Ref(RIS.Equal(0), 10).Dummy)).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#60;int&#62;.Is.Equal(1), Arg&#60;string&#62;.Is.Equal(&#34;Hello&#34;), out Arg&#60;int&#62;.Out(10).Dummy)).Return(1);

// **** DYNAMIC MOCKS ***
// A mock is an object which we can set expectations on and will assert that those expectations have been 
// Dynamic Mock provides easier syntax and does not require stubbing/expecting all methods

mocks.CreateMock&#60;T&#62;(); 

// Assert Was Called
mock.AssertWasCalled(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.Anything));
mock.AssertWasCalled(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.NotNull));
mock.AssertWasCalled(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.Equal(theModel)));
mock.AssertWasNotCalled(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.Null));       
mock.AssertWasCalled(x =&#62; x.AReadonlyPropery);
mock.AssertWasCalled(x =&#62; x.AProperty);
mock.AssertWasCalled(x =&#62; x.AProperty = 9);
mock.AssertWasCalled(x =&#62; x.EventHandler += Arg&#60;AnEvent&#62;.Is.Anything); // Event was registered

// Expect &#38; Verify
mock.Expect(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.Anything));
mock.Expect(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.NotNull));                    
mock.Expect(p =&#62; p.Add(Arg&#60;AnotherModel&#62;.Is.Equal(theModel)));
mock.Expect(x =&#62; x.AReadonlyPropery).Return(9);
mock.Expect(x =&#62; x.AProperty).Return(9);
mock.Expect(x =&#62; x.AProperty).SetPropertyAndIgnoreArgument();
mock.Expect(x =&#62; x.AProperty).SetPropertyWithArgument(11);

mock.VerifyAllExpectations()
</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Day 14 - Rhino Mocks]]></title>
<link>http://lukewickstead.wordpress.com/2013/03/10/day-14-rhino-mocks/</link>
<pubDate>Sun, 10 Mar 2013 16:18:12 +0000</pubDate>
<dc:creator>LW</dc:creator>
<guid>http://lukewickstead.wordpress.com/2013/03/10/day-14-rhino-mocks/</guid>
<description><![CDATA[The Source Code This post is part of my Dot Net On Linux posts. All the source code is available on]]></description>
<content:encoded><![CDATA[<h2>The Source Code</h2>
<p><a title="Dot Net on Linux" href="http://lukewickstead.wordpress.com/2012/11/01/dot-net-on-linux/">This post is part of my Dot Net On Linux posts</a>. All the source code is available on GitHub <a href="https://github.com/lukewickstead/DOT-NET-on-Linux">here</a></p>
<h2>Intro</h2>
<p>This post is just to point you to my <a title="Delegates to Lambdas." href="http://lukewickstead.wordpress.com/2013/01/26/delegates-to-lambdas/">H</a>owTo on Rhino Mocks and also to make the code available as part of the .Net on Linux post series.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[HowTo - Rhino Mocks]]></title>
<link>http://lukewickstead.wordpress.com/2013/03/10/howto-rhino-mocks/</link>
<pubDate>Sun, 10 Mar 2013 16:11:41 +0000</pubDate>
<dc:creator>LW</dc:creator>
<guid>http://lukewickstead.wordpress.com/2013/03/10/howto-rhino-mocks/</guid>
<description><![CDATA[Source Code All source code can be found on GitHub here. My cheat sheet in generics can be found her]]></description>
<content:encoded><![CDATA[<h2>Source Code</h2>
<p>All source code can be found on GitHub <a href="https://github.com/lukewickstead/DOT-NET-on-Linux">here.</a></p>
<p>My cheat sheet in generics can be found <a title="Generics Cheat Sheet" href="http://lukewickstead.wordpress.com/2013/01/18/generics-cheat-sheet/">here</a> while some code examples in generics can be found in my post <a title="Day 9 – Generics" href="http://lukewickstead.wordpress.com/2013/01/19/day-9-generics/">here</a>.</p>
<p>This is part of my HowTo in .NET seriies. An overview can be seen <a title=".NET HowTos" href="http://lukewickstead.wordpress.com/2013/01/13/net-howtos/">here</a>,</p>
<h1>Intro</h1>
<p>Rhino Mocks is a mocking framework for .Net. In essence a mocking framework allows you to stub a complex expensive resource such as a database or webserver. However mocking frameworks can allow you to completely isolate a SUT during testing. Mocking frameworks also allow the creation of expectations of methods calls between a mock and the SUT; the unit test will then fail if the expected method calls were not made or made but with the wrong parameter values. Testing can then be behavioural as well as state based. This how to looks at the syntax for version 3.6 and above which does not require the record and playback syntax.</p>
<h1>Stubs</h1>
<h2>Stub A Method</h2>
<p>The simplest explanation of when to stub is when a resource such as a database or web service is encountered; something which is expensive to consume when unit testing. Providing a stub for a class which consumes a database can allow us to substitute this at run time making unit testing quicker and easier but also it can allow us to very easily create complex unit tests with a wealth of data which is very easy to set up without having to create test data within a database. The following simple example mocks an interface called method called Do() on interface ISimpleModel which takes no parameters and when called returns 1 as an integer. MockRepository is used to create a fake or stubbed instance of ISimpleModel, it is upon this that we are required to call our functions. If we were stubbing a class and not an interface then one thing to note is that you would not get any functionality of the class. You can not mix and match functionality of the class and stubbed functions.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
var sut = MockRepository.GenerateStub();
sut.Stub(x =&#62; x.Do()).Return(1);
</pre>
<h2>Stub A Property</h2>
<p>Get functions of properties can be stubbed. The following syntax allows stubbing of a readonly property (get only).</p>
<pre class="brush: csharp; title: ; notranslate" title="">
var sut = MockRepository.GenerateStub();
sut.Stub(x =&#62; x.AReadonlyPropery).Return(1);
</pre>
<p>The following syntax allows stubbing of a get method of a property.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
var sut = MockRepository.GenerateStub();
sut.AProperty = 2;  // Stubs a Get_AProperty as 2
Assert.That(sut.AProperty.Equals(2));
</pre>
<p>It is not required to stub set methods. Any methods can be consumed automatically without stubbing them, only if we need a return value other than default(T) for value types and null for reference types do you need to stub the method. Set methods return void so stubbing this is not required.</p>
<h2>Arguments</h2>
<p>If our stubbed methods takes arguments then we need to provide for them.</p>
<h3>Ignoring Arguments</h3>
<p>In the simplest form we might not care what values the parameters take and can simply state that they can be anything. Allow the argument to be Anything.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Is.Anything)).Return(1);
</pre>
<p>Call IgnoreArguments() will make any constrained arguments parameters have their constraints ignored.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Is.Equal(1))).IgnoreArguments().Return(1);
</pre>
<h3>Constrained Arguments</h3>
<p>Constrained arguments allow us to return different data based upon the method parameter values which it is called upon. When all parameters are matched the return is made. If multiple stubs are matched then the first registered stub instance is used to determine the return value.</p>
<h4>Is</h4>
<p>Is constants provide predicates for literal and reference types. The following is a quick run through of the Is argument constraints. Equal and NotEqual for equality based comparison.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Is.Equal(1))).Return(1);
sut.Stub(x =&#62; x.Do(Arg.Is.NotEqual(1))).Return(10);
</pre>
<p>Comparison between two literals.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Is.GreaterThanOrEqual(10))).Return(1);
sut.Stub(x =&#62; x.Do(Arg.Is.GreaterThan(10))).Return(2);
sut.Stub(x =&#62; x.Do(Arg.Is.LessThanOrEqual(10))).Return(1);
sut.Stub(x =&#62; x.Do(Arg.Is.LessThan(10))).Return(2);
</pre>
<p>Comparison to null with Is.Null and Is.NotNull.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.DoIFoo(Arg.Is.Null)).Return(1);
sut.Stub(x =&#62; x.DoIFoo(Arg.Is.NotNull)).Return(2);
</pre>
<p>IsTypeOf to determine if the type is of the required type. In this example Moo and Foo both implement IFoo Whig is the parameter type. Based upon whether Foo or Moo is passed in we can alter our return value.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.DoIFoo(Arg.Is.TypeOf)).Return(1);
sut.Stub(x =&#62; x.DoIFoo(Arg.Is.TypeOf)).Return(2);
</pre>
<p>Identity comparison with Same and NotSame functions.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.DoIFoo(Arg.Is.Same(foo))).Return(1);
sut.Stub(x =&#62; x.DoIFoo(Arg.Is.NotSame(foo))).Return(2);
</pre>
<h4>List</h4>
<p>The List functions allow us to provide predicates upon elements which implement IEnumerable and IEnumerable. I aliased RIS as &#8216;using RIS = Rhino.Mocks.Constraints.Is;&#8217; to make a distinction between NUnit and Rhino Mocks Is. The simplest form of List is the count which allows us to compare the element count against an Is constraint. Any of the Is constraints which predicate numbers can be used; Equal IsLessThan etc. Below we stub Do(IList t) twice once for when the parameter contains no elements and another for one element.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg&#62;.List.Count(RIS.Equal(0)))).Return(0);
sut.Stub(x =&#62; x.Do(Arg&#62;.List.Count(RIS.Equal(1)))).Return(1);
</pre>
<p>Element allows comparison of element at a position to an Is constraint. The first parameter is the element position and the second parameter is an Is constraint.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg&#62;.List.Element(0, RIS.Equal(1)))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#62;.List.Element(1, RIS.GreaterThanOrEqual(2)))).Return(2);
</pre>
<p>Equal allows comparison of a collection to another.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg&#62;.List.Equal(new int[] { 1, 2, 3 }))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#62;.List.Equal(new int[] { 4, 5, 6 }))).Return(2);
</pre>
<p>IsIn allow predicating if an element is contained within the collection.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg&#62;.List.IsIn(1))).Return(1);
sut.Stub(x =&#62; x.Do(Arg&#62;.List.IsIn(4))).Return(2);
</pre>
<p>OneOf allows predicate for any elements in both collections;</p>
<p>if one or more elements are found in both collections then the predicate is deemed as passed.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.List.OneOf(new int[] { 1, 2, 3 }))).Return(1);
sut.Stub(x =&#62; x.Do(Arg.List.OneOf(new int[] { 4, 5, 6 }))).Return(2);
</pre>
<h4>Matches</h4>
<p>When the predicate is more complex or the built in functionality is not sufficient the Matches function provides more scope by taking a Predicate delegate; if you can write it you can predicate it!</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Matches(y =&#62; y &#62; 5))).Return(1);
</pre>
<h2>Repeat</h2>
<p>It is possible to set up the stubbing for x number of repetition; thus we can return different results dependant upon the call iteration. The methods Once(), Twice() and Times(int x) are provided.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
mock = MockRepository.GenerateStub();
mock.Stub(x =&#62; x.Do()).Return(1).Repeat.Once();
mock.Stub(x =&#62; x.Do()).Return(2).Repeat.Twice();
mock.Stub(x =&#62; x.Do()).Return(3).Repeat.Times(3);
</pre>
<h2>ByRef and Out Parameters</h2>
<p>By Ref parameters can be implemented by utilising the ref keyword along with the Ref and Dummy methods.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Is.Equal(1), ref Arg.Ref(RIS.Equal(0), 10).Dummy)).Return(1);
</pre>
<p>Out parameters can be implemented by utilising the out keyword along with the Out and Dummy methods.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(Arg.Is.Equal(1), Arg.Is.Equal(&#34;Hello&#34;), out Arg.Out(10).Dummy)).Return(1);
</pre>
<h2>By Literal</h2>
<p>Though highly discouraged stubbing by literals can also be utilised.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
sut.Stub(x =&#62; x.Do(1).Return(1);
sut.Stub(x =&#62; x.Do(&#34;Foo&#34;).Return(2);
</pre>
<h1>Mocks</h1>
<p>A Mock is similar to a Stub, in fact it contains all the functionality mentioned above however mocks can record required behaviour and fail a unit test if the required behaviour is not called upon by the SUT. For example If we have a class A which requires to call two methods on class B with certain parameters we can ensure that all of this behaviour is called or fail the unit test. We can either place expectation calls on the mock prior to the unit test act or we can make assertions of function calls during the assert.</p>
<h2>Assert Was Called</h2>
<p>AssertWasCalled provides a way asserting that a function call with required parameters was called. If a return value is required then this method can not be used.</p>
<h3>Argument Constraints</h3>
<p>All argument constraints mentioned previously in the stubs section can and should be utilised along with the AssertWasCalled function. If the function was not called with the parameter constraints then an exception is thrown and as such the unit test fails. The following example shows how to ensure that a function is called ignoring the parameter values.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenArgumentsIsAnything()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasCalled(p =&#62; p.Add(Arg.Is.Anything));
 }
</pre>
<p>The following example shows how to ensure that a function is called ensuring that the parameter is not null.</p>
<pre class="brush: csharp; title: ; notranslate" title="">

[Test]
public void WhenArgumentsIsNotNull()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasCalled(p =&#62; p.Add(Arg.Is.NotNull));

 }
</pre>
<p>The following example shows how to ensure that a function is called ensuring that the parameter is equal to a reference type.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenArgumentsIsEqual()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasCalled(p =&#62; p.Add(Arg.Is.Equal(theModel)));

 }
</pre>
<h3>Assert Was Not Called</h3>
<p>AssertWasNotCalled works exactly the same as AssertWasCalled however it throws an exception and fails the unit test if the method with argument constraints was called.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenNotCalled()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasNotCalled(p =&#62; p.Add(Arg.Is.Null));

}
</pre>
<h3>Properties</h3>
<p>The syntax for asserting that a readonly property or get method of a property is exactly the same as each other (unlike when we look at Expect and Verify!).</p>
<pre class="brush: csharp; title: ; notranslate" title="">

[Test] public void WhenReadonlyProperty()
{
	var sut = MockRepository.GenerateMock();

 	var foo = sut.AReadonlyPropery;

 	Assert.That(foo.Equals(0));

 	sut.AssertWasCalled(x =&#62; x.AReadonlyPropery);

 }
</pre>
<p>&#160;</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenProperyGetCalled()
{
	var sut = MockRepository.GenerateMock();

 	Assert.That(sut.AProperty, Is.EqualTo(0));

 	sut.AssertWasCalled(x =&#62; x.AProperty);

 }
</pre>
<p>Asserting that a set method of a property is called with a literal value.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenProperySetCalled()
{
	var sut = MockRepository.GenerateMock();

 	sut.AProperty = 9;

 	Assert.That(sut.AProperty, Is.EqualTo(0));

 	sut.AssertWasCalled(x =&#62; x.AProperty = 9);

 }
</pre>
<h2>Expect and Verify</h2>
<p>Expect and Verify has two advantages over the AssertWasCalled style syntax. Firstly it allows stubbing inline with the Expect function call and secondly it allows setting the expectations as part of the assign stage along with other Stub functionality which might be required. The Expect() method allows all argument constraints as shown in the stub section above and works exactly the same as stub however if when VerifyAllExpectations is called as part of the assert section of the unit test any configured expects which have not been called or called with the required parameters, an exception is thrown and the unit test fails. Unlike AssertWasCalled syntax no equivalent functionality for AssertWasNotCalled is provided.</p>
<h3>Argument Constraints</h3>
<p>All argument constraints are available. Below are a few examples The following example shows how to ensure that a function when it does not matter what parameters are used.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenArgumentIsAnything()
{
	IModelRepository mock = MockRepository.GenerateMock();

	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	mock.Expect(p =&#62; p.Add(Arg.Is.Anything));

 	modelCreator.CreateModel(theModel);

 	mock.VerifyAllExpectations();

 }
</pre>
<p>The following example shows how to ensure that a function only requires that the function is called without a reference type being null.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenArgumentIsNotNull()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	mock.Expect(p =&#62; p.Add(Arg.Is.NotNull));

 	modelCreator.CreateModel(theModel);

 	mock.VerifyAllExpectations();

 }
</pre>
<p>The following example shows how to ensure that a function with equality check for a reference type.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test] public void WhenArgumentIsEqualTo()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = &#34;Test&#34; };

 	mock.Expect(p =&#62; p.Add(Arg.Is.Equal(theModel)));

 	modelCreator.CreateModel(theModel);

 	mock.VerifyAllExpectations();

 }
</pre>
<p>The following example shows how to ensure that a function is called with a number type parameter equal to 9.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenReadonlyPropertyCalled()
{
	var sut = MockRepository.GenerateMock();

	sut.Expect(x =&#62; x.AReadonlyPropery).Return(9);

 	Assert.That(sut.AReadonlyPropery, Is.EqualTo(9));

 	sut.VerifyAllExpectations();
}
</pre>
<h3>Properties</h3>
<p>The first example shows how to place an expectation on a get method of a property.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenPropertyGetCalled()
{
	var sut = MockRepository.GenerateMock();

 	sut.Expect(x =&#62; x.AProperty).Return(9);

 	Assert.That(sut.AProperty, Is.EqualTo(9));

 	sut.VerifyAllExpectations();

 }
</pre>
<p>This example shows how to place an expectation on a set method while ignoring the parameter value.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenPropertySetCalledWithIgnoreArguments()
{
	var sut = MockRepository.GenerateMock();

 	sut.Expect(x =&#62; x.AProperty).SetPropertyAndIgnoreArgument();

 	sut.AProperty = 1;

 	sut.VerifyAllExpectations();

 }
</pre>
<p>This example shows how to place an expectation on a set method with an explicit value.</p>
<pre class="brush: csharp; title: ; notranslate" title="">
[Test]
public void WhenPropertySetCalledWithArguments()
{
	var sut = MockRepository.GenerateMock();

 	sut.Expect(x =&#62; x.AProperty).SetPropertyWithArgument(11);

 	sut.AProperty = 11;

 	sut.VerifyAllExpectations();
 }
</pre>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Agile Scrum Transition With Legacy Code]]></title>
<link>http://johnbenecke.com/2013/03/07/agile-scrum-transition-with-legacy-code/</link>
<pubDate>Thu, 07 Mar 2013 09:13:36 +0000</pubDate>
<dc:creator>John von Benecke</dc:creator>
<guid>http://johnbenecke.com/2013/03/07/agile-scrum-transition-with-legacy-code/</guid>
<description><![CDATA[If you are working for an organization that has an existing software solution developed under a Wate]]></description>
<content:encoded><![CDATA[<p>If you are working for an organization that has an existing software solution developed under a Waterfall methodology – but have determined that Agile Scrum is the right way forward – what are you going to do with all your legacy code, and how easy will the change in methodology be?</p>
<p>People understand slightly different things when they hear the term ‘legacy code’. For some people…it is code that is no longer supported, for others – it is source code inherited from someone else or source code from an older version of the software.</p>
<p>Michael Feathers (Working Effectively with Legacy Code ISBN 0-13-117705-2) introduced what for me is a more insightful definition of legacy code – that speaks directly to the underlying problem that working with it creates. His definition of <b>Legacy Code</b> is “<i>code without tests</i>”. He goes on to say <i>“Codes without tests is bad code. It doesn’t matter how well written it is; it doesn’t matter how pretty or object-oriented or well encapsulated it is. With tests, we can change the behavior of our code quickly and verifiably. Without them, we really don’t know if our code is getting better or worse”</i>.</p>
<p>Because Agile Scrum can only deliver on its promise of ‘faster and better’ software if the continuous improvement feedback loops are timely and accurate…. transitioning legacy code into an Agile Scrum environment presents significant problems.</p>
<p>The special problem of legacy code is that it was never designed to be testable. It is often a huge convoluted mess of spaghetti code, where it is very difficult or downright impossible to isolate small parts to be unit tested. So before unit testing, you need to refactor the code to make it more testable.</p>
<p>However, in order to refactor safely, you must have unit tests to verify that you haven&#8217;t broken anything with your changes&#8230; This is the catch 22 of legacy code.</p>
<p>In order to break out of this catch 22 situation – there are a number of techniques that can be deployed so that you can start to insert good quality unit tests into your code. Good quality units tests are test that:</p>
<ul>
<li>Run very fast</li>
<li>Help us localize problems.</li>
</ul>
<p>When you start to introduce unit tests – you should expect to take a few backward steps. As you begin to break down the dependencies and introduce barriers into your code so that you can start to insert new unit tests…these changes to the code can often make the code initially ugly or more complex, but breaking dependencies is the medicine that will make the code better in the long run.</p>
<p>Generally, when we want to get tests in place, there are two reasons to break dependencies: <i>sensing</i> and <i>separation</i></p>
<ul>
<li><b>Sensing</b> – we break dependencies to <i>sense</i> when we can’t access values our code computes</li>
<li><b>Separation</b> – we break dependencies to <i>separate</i> when we can’t even get a piece of code into a test harness to run.</li>
</ul>
<p>One of the biggest challenges in getting legacy code under test is breaking dependencies. When we are lucky, the dependencies are small and localized…. but more often than not…you are confronted with a mass of dependencies throughout the code base.</p>
<p>To address this problem, we need to find or introduce seams in our code. <b>A seam is a place in the code where you can change the behavior of your program without modifying the code itself</b>. If we can replace behavior at seams, we can selectively exclude dependencies in our tests. We can also run other code where those dependencies where if we want to sense conditions in the code and write tests against those conditions. Often this work will help you get just enough tests in place to support more aggressive or challenging changes.</p>
<p>This process of refactoring your code to make it ‘test friendly’ is a significant investment that your organization will have to make, but it is a prerequisite for successful Agile Scrum development. Great results from Agile Scrum require great feedback loops…. and those feedback loops depend on test friendly software…which by definition…. excludes Feathers’ definition of ‘legacy code’.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[All Your Mocks are Evil!!]]></title>
<link>http://stephenhaunts.com/2013/03/07/all-your-mocks-are-evil/</link>
<pubDate>Thu, 07 Mar 2013 06:05:32 +0000</pubDate>
<dc:creator>Stephen Haunts</dc:creator>
<guid>http://stephenhaunts.com/2013/03/07/all-your-mocks-are-evil/</guid>
<description><![CDATA[In unit testing, all mocks are evil! Now there&#8217;s a controversial statement to start a blog pos]]></description>
<content:encoded><![CDATA[<p style="text-align:justify;">In unit testing, all mocks are evil! Now there&#8217;s a controversial statement to start a blog post with, but let me explain. I am writing this from my own experience as a software developer and a leader of software developers. This is the sort of thing that software religious wars are made of, so if you agree, or disagree, I would love for you to share your thoughts in the comments.</p>
<p style="text-align:center;"><a href="http://stephenhaunts.files.wordpress.com/2013/03/evil.jpg"><img class="aligncenter  wp-image-264" alt="evil" src="http://stephenhaunts.files.wordpress.com/2013/03/evil.jpg?w=512&#038;h=384" width="512" height="384" /></a></p>
<p style="text-align:justify;">I think Mocking libraries, although very powerful, can enable developers to over complicate their unit tests. Unit tests should be short and easy to understand. I have lost count of the times where I have seen a developer mock out more than they need to because of excessive class coupling in their code. Just because you can mock out any object doesn&#8217;t mean that you should and avoid reducing excessive coupling.</p>
<p style="text-align:justify;"><!--more--></p>
<p style="text-align:justify;">I have also seen mocks being used by developers that abuse the layering and design of their solution. As an example, we have a 3rd part consultancy company writing some code for us to help augment our team numbers. Just recently myself and another group of leads were reviewing this consultancies code. They were developing a web service and on the face of it, were composing their code in layers. They had a service layer, calling a business logic layer, calling a data access layer. All sounding very familiar and normal at this point.</p>
<p style="text-align:justify;">What we then found was they had huge amounts of business logic that had been put into the data access layer and not in the business logic layer. This raised quite a few alarm bells, so we looked at the tests. What we found was not nice. They had written a series of tests for the business logic layer that completely mocked out the data access layer. Normally this is fine as you don&#8217;t want to actually hit a database in a unit test, but what they had done was actually mock out the majority of their business logic which meant the tests were not doing anything useful at all.</p>
<p style="text-align:justify;">Whilst I am picking on this one example, this is not the only case where I have seen mocking libraries used for evil.</p>
<p style="text-align:justify;">So, what do I prefer instead. My own preference, and this is one I practice with my own team, is to write code to interfaces and use simple dependency injection to inject implementations into your code. By doing this instead I feel you have much more control over your code and your tests generally end up easier to write once you get used to this way of coding. I have written another post on <a title="Simple Dependency Injection by Stephen Haunts" href="http://stephenhaunts.com/2013/01/14/simple-dependency-injection/" target="_blank">simple dependency injection</a>, so I recommend reading that.</p>
<p style="text-align:justify;">In my team I have pretty much outlawed the use of mocking libraries on new or previously refactored and cleaned code, there just is no need to use them as we practice writing well designed code written to interfaces and following the <a title="SOLID Principles" href="http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29" target="_blank">SOLID principles</a>.</p>
<p style="text-align:center;"><a href="http://stephenhaunts.files.wordpress.com/2013/03/solid.png"><img class="aligncenter  wp-image-265" alt="solid" src="http://stephenhaunts.files.wordpress.com/2013/03/solid.png?w=512&#038;h=160" width="512" height="160" /></a></p>
<p>SOLID is a set of design principles that every software developer who practices object oriented design should follow. If you follow these principles then you will find that you really don&#8217;t need to use mocking libraries (on new code at least, more on that later). The SOLID principles are:</p>
<p style="padding-left:30px;"><b>S</b> &#8211; <i>Single responsibility principle</i>. An object should have only a single responsibility.</p>
<p style="padding-left:30px;"><b>O </b>- <i>Open/Closed principle</i>. Objects should be open for extension, but closed for modification.</p>
<p style="padding-left:30px;"><b>L</b> &#8211; <i>Liskov substitution principle</i>. Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. This is also known as design by contract.</p>
<p style="padding-left:30px;"><b>I</b> &#8211; <i>Interface segregationpPrinciple</i>. Many client specific interfaces are better than one general purpose interface.</p>
<p style="padding-left:30px;text-align:justify;"><b>D</b> &#8211; <i>Dependency inversion principle</i>. One should depend on abstractions. Do not depend upon their concretions. This is where you decouple comes into play.</p>
<p style="text-align:justify;">A very good book that covers the SOLID principles is <a title="Clean Code by Robert C. Martin" href="http://www.amazon.co.uk/gp/product/0132350882/ref=as_li_ss_tl?ie=UTF8&#38;camp=1634&#38;creative=19450&#38;creativeASIN=0132350882&#38;linkCode=as2&#38;tag=stehaucodinth-21" target="_blank">Clean Code, by Robert C. Martin</a>. I recommend that every software developer should read this book.</p>
<div id="attachment_263" class="wp-caption aligncenter" style="width: 283px"><a href="http://stephenhaunts.files.wordpress.com/2013/03/clean-code.jpg"><img class=" wp-image-263 " title="Clean Code by Robert C. Martin" alt="Clean Code by Robert C. Martin" src="http://stephenhaunts.files.wordpress.com/2013/03/clean-code.jpg?w=273&#038;h=363" width="273" height="363" /></a><p class="wp-caption-text">Clean Code by Robert C. Martin</p></div>
<p style="text-align:justify;">As I stated above, if you rigorously follow these principles and ingrain them into the way you right code, you will find that you genuinely do not need to resort to mocking libraries to mock out dependencies as your code will naturally start to become decoupled. I would even go as far as saying that if you feel the need to use a mocking library then that should be a code smell indicating there is a design problem.</p>
<p style="text-align:justify;">Mocking libraries do have their place though. As with most tools, they are a valuable tool in your tool box for specific purposes. If you inherit a large, badly written legacy system, otherwise known as a <em><strong>Big Ball of Mud</strong></em>, the first thing you want to do before changing the code is get some tests around what is there already. These tests are called characteristics tests. This is where you need to test what the current functionality does. This functionality may be wrong or buggy, but you want to get a test suite in place so that you know whether you have broken/changed anything as part of your refactoring. Normally because of excessive class coupling you will need to use a mocking library to write these tests. In this scenario I think mocking libraries are perfect and this is when I would use them, but as you start refactoring your code and trying to introduce some of the solid principles you need to plan for how you are going to remove these mocks and write simpler tests.</p>
<p style="text-align:justify;">There is a great book on all of this called <a title="Brownfield Application Development in .NET by Donald Belcham" href="http://www.amazon.co.uk/gp/product/1933988711/ref=as_li_ss_tl?ie=UTF8&#38;camp=1634&#38;creative=19450&#38;creativeASIN=1933988711&#38;linkCode=as2&#38;tag=stehaucodinth-21" target="_blank">Brownfield Application Development in .NET by Donald Belcham</a> that covers this exact subject.</p>
<div id="attachment_262" class="wp-caption aligncenter" style="width: 343px"><a href="http://stephenhaunts.files.wordpress.com/2013/03/brownfield.png"><img class="size-full wp-image-262" title="Brownfield Application Development in .NET by Donald Belcham" alt="Brownfield Application Development in .NET by Donald Belcham" src="http://stephenhaunts.files.wordpress.com/2013/03/brownfield.png?w=333&#038;h=392" width="333" height="392" /></a><p class="wp-caption-text">Brownfield Application Development in .NET by Donald Belcham</p></div>
<p style="text-align:justify;">That concludes my views on mocking frameworks. I am sure there are developers reading this thinking &#8220;Hey, I use mocks and can write decent tests that work at the correct layers&#8221;, and I am sure you can. Part of my view on this subject comes from leading mixed ability teams of developers where I have seen these libraries abused so many times before. I now encourage my team to work with the SOLID principles and write tests the good old fashioned way.</p>
<p style="text-align:justify;">I know this is a subject that developers are passionate about. I am not claiming this way is the only way, but it is the way that works for me and my team. If you have any views on this, then I invite you to share them in the comments for this post.</p>
<p style="text-align:center;">
]]></content:encoded>
</item>
<item>
<title><![CDATA[Definition of a Good Unit Test]]></title>
<link>http://adamprescott.net/2013/03/06/definition-of-a-good-unit-test/</link>
<pubDate>Wed, 06 Mar 2013 14:00:08 +0000</pubDate>
<dc:creator>Adam Prescott</dc:creator>
<guid>http://adamprescott.net/2013/03/06/definition-of-a-good-unit-test/</guid>
<description><![CDATA[I&#8217;m constantly encouraging developers around me to embrace test-driven development and automat]]></description>
<content:encoded><![CDATA[<p>I&#8217;m constantly encouraging developers around me to embrace test-driven development and automated unit testing. However, there&#8217;s one very important thing I&#8217;ve neglected to include in my evangelizing: a definition for what constitutes a good unit test.</p>
<p>A big problem that I think a lot of developers run into is that they&#8217;re writing tests but aren&#8217;t realizing any value from them. Development takes longer because they have to write tests, and when requirements change it takes longer because they have to refactor tests. Maintenance and warranty work is slower, too, because of the additional upkeep from failing tests created with every little change.</p>
<p>These problems mostly exist because of bad unit tests that are written due to insufficient knowledge of what makes a good test. Here&#8217;s a list of properties for a good unit test, taken from <a href="http://artofunittesting.com/definition-of-a-unit-test/">The Art of Unit Testing</a>:</p>
<blockquote>
<ul>
<li>Able to be fully <strong>automated</strong></li>
<li>Has full control over all the pieces running (Use mocks or stubs to achieve this isolation when needed)</li>
<li>Can be run in any <strong>order</strong>  if part of many other tests</li>
<li>Runs in <strong>memory</strong> (no DB or File access, for example)</li>
<li><strong>Consistently</strong> returns the same result (You always run the same test, so no random numbers, for example. save those for integration or range tests)</li>
<li>Runs <strong>fast</strong></li>
<li>Tests a <strong>single logical concept</strong> in the system</li>
<li><strong>Readable</strong></li>
<li><strong>Maintainable</strong></li>
<li><strong>Trustworthy</strong> (when you see its result, you don’t need to debug the code just to be sure)</li>
</ul>
</blockquote>
<p>This is a great list that you can use to gut-check your unit tests. If a test meets all of these criteria, you&#8217;re probably in good shape. If you&#8217;re violating some of these, refactoring is probably required in your test or in your design, particularly in the cases of <em>Has full control over all the pieces running</em>,<em> Runs in memory</em>, and <em>Tests a single logical concept in the system</em>.</p>
<p>When I see developers struggling with unit tests and test-driven development, it&#8217;s usually due to test &#8220;backfilling&#8221; on a poorly-designed or too-complex method. They don&#8217;t see value because, in their minds, the work is already done and they&#8217;re having to do additional work just to get it unit tested. These methods and objects are violating the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibility principle</a> and sometimes have many different code paths and dependencies. That complexity makes writing tests hard because you have to do so much work upfront in terms of mocking and state preparation, and it&#8217;s really difficult to cover each and every code path. It also makes for fragile tests because testing specific parts of a method rely on a test&#8217;s ability so successfully navigate its way through the logic in the complex method; if an earlier part of the method changes, you now have to refactor unrelated tests to re-route them back to the code they&#8217;re testing. (Tip: Avoid problems like this by writing tests first!)</p>
<p>Whether you&#8217;re just getting with unit tests or a grizzled veteran, you can benefit from using this list of criteria as a quality measuring stick for the tests you write. High-quality tests that verify implemented features will result in a stable application. Designs will become better and more maintainable because you&#8217;ll be able to modify specific functionality without affecting the surround system the same way that you&#8217;re able to test it. You won&#8217;t have to worry about other developers breaking functionality you&#8217;ve added, and you won&#8217;t have to worry about breaking functionality they&#8217;ve added. You&#8217;ll be able to make a modification that affects the entire system with a high-level of confidence. I&#8217;d venture to say that virtually every aspect of software development is better when you&#8217;ve got good tests.</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[When It Walks Like A Duck]]></title>
<link>http://jemappellewendyi.wordpress.com/2013/03/06/when-it-walks-like-a-duck/</link>
<pubDate>Wed, 06 Mar 2013 05:23:45 +0000</pubDate>
<dc:creator>jemappellewendyi</dc:creator>
<guid>http://jemappellewendyi.wordpress.com/2013/03/06/when-it-walks-like-a-duck/</guid>
<description><![CDATA[On my new, assume commute home tonight, on my new awesome bike, I was reminded of something that is]]></description>
<content:encoded><![CDATA[<p><a href="http://jemappellewendyi.files.wordpress.com/2013/03/photo-1.jpg"><img class="alignleft size-thumbnail wp-image-1629" style="border:5px solid white;" alt="photo (1)" src="http://jemappellewendyi.files.wordpress.com/2013/03/photo-1.jpg?w=150&#038;h=112" width="150" height="112" /></a>On my new, assume commute home tonight, on my new awesome bike, I was reminded of something that is more part of my day job, <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a>.</p>
<p>I was less than half way home, enjoying the freedom of my new ride, when a passenger in a car a couple of lanes over caught my attention. She wanted to know where Pier 39 was. Despite not being an SF resident, I have been here enough that it was an easy question to answer. And that&#8217;s when duck typing came to mind.</p>
<p>Just as we say when it <strong>walks like a duck and quacks like a duck, it must be a</strong> <strong>duck</strong>, it seems as if <strong>when she commutes like a SFer and she must be a SFer</strong>. In this case, not exactly true, but it got the mission accomplished. Perhaps the unit test gave a false positive, but maybe I should also stop with these crazy analogies.<strong><br />
</strong></p>
<p>And, given that, I just want to say that at this point I wish I would have bought this bike sooner. Not only will my commute time likely go done, I&#8217;ll be getting some reasonable exercise at the same time. And I won&#8217;t be at all upset that I am trading off a bit of upper arm strength building while bracing for sudden starts and stops on an almost always packed as sardines bus for some good old fashioned aerobic work. This is even more true since I haven&#8217;t been able to run lately due to my foot being overly sensitive recently.</p>
<p>Sadly it is supposed to be raining in the morning, hopefully it will have tapered off by commute time, fingers crossed.</p>
<p>Wendy</p>
]]></content:encoded>
</item>
<item>
<title><![CDATA[Google OAuth and jUnit]]></title>
<link>http://sumeet70.wordpress.com/2013/03/04/google-oauth-and-junit/</link>
<pubDate>Tue, 05 Mar 2013 04:23:21 +0000</pubDate>
<dc:creator>sumeet70</dc:creator>
<guid>http://sumeet70.wordpress.com/2013/03/04/google-oauth-and-junit/</guid>
<description><![CDATA[I recently ran into a very simple problem with seemingly not so simple answer. I wanted to automate]]></description>
<content:encoded><![CDATA[<p>I recently ran into a very simple problem with seemingly not so simple answer. I wanted to automate my integration test suite (jUnit) but my application uses Google Drive API with three legged oauth. That requires me to manually sign in into the browser and retrieve authentication token. Which means that I cannot run my CI without manual intervention.</p>
<p>So headless browser was my answer to the situation. Go grab HtmlUnit from here <a title="http://sourceforge.net/projects/htmlunit/" href="http://sourceforge.net/projects/htmlunit/">http://sourceforge.net/projects/htmlunit/</a></p>
<p>Once you add the reference to the downloaded jars it becomes a straight forward process. Basically this snippet below walks through the process of clicking through the pages and retrieveing the auth token.</p>
<p>This code assumes that you are not already logged into your oauth account, in which case, some conditional handling will be required. I will try to update the snippet soon. Meanwhile add the following lines to your authentication code to get the auth token automagically !!!</p>
<p>GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE)).setAccessType(&#8220;online&#8221;).setApprovalPrompt(&#8220;auto&#8221;).build();<br />
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();</p>
<p>HtmlPage page = webClient.getPage(url);<br />
HtmlSubmitInput signInButton = (HtmlSubmitInput)page.getElementByName(&#8220;signIn&#8221;);<br />
HtmlTextInput userNameField = (HtmlTextInput)page.getElementByName(&#8220;Email&#8221;);<br />
HtmlPasswordInput passwordField = (HtmlPasswordInput)page.getElementByName(&#8220;Passwd&#8221;);</p>
<p>userNameField.setValueAttribute(&#8220;YOUR_USER_NAME&#8221;);<br />
passwordField.setValueAttribute(&#8220;YOUR_PASSWORD&#8221;);</p>
<p>HtmlPage allowAccessPage = signInButton.click();<br />
HtmlButton allowAccessButton = (HtmlButton)allowAccessPage.getElementById(&#8220;submit_approve_access&#8221;);<br />
HtmlPage tokenPage = allowAccessButton.click();</p>
<p>HtmlTextInput tokenElement = (HtmlTextInput)tokenPage.getElementById(&#8220;code&#8221;);<br />
String code = tokenElement.getText();</p>
<p>webClient.closeAllWindows();<br />
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();<br />
credential = new GoogleCredential().setFromTokenResponse(response);</p>
<p>And you are all set.</p>
]]></content:encoded>
</item>

</channel>
</rss>
