<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Christopher Bennage : TDD</title><link>http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx</link><description>Tags: TDD</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Improving Asynchronous Tests for Silverlight</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2011/01/17/improving-asynchronous-tests-for-silverlight.aspx</link><pubDate>Mon, 17 Jan 2011 16:29:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:64651</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>11</slash:comments><description>&lt;p&gt;First a confession, and I know I’ll invoke shame for this one: I have done Very Little Testing with Silverlight. I won’t bore you with reasons or excuses, but I wasn’t up on the state of unit testing in Silverlight until very recently. (In fact, I might&amp;#160; still be missing some chunks.)&lt;/p&gt;  &lt;h3&gt;The Problem&lt;/h3&gt;  &lt;p&gt;Last week, I started writing some tests for &lt;a title="an Open Source (with a commercial option) document database for the .NET/Windows platform" href="http://www.ravendb.net/" target="_blank"&gt;Raven DB&lt;/a&gt;. I won’t call them ‘unit’ tests because they were really ‘integration’ tests. Specifically, I wanted to test the budding Silverlight client for Raven. This mean that my tests had to make calls to the Raven server, wait for the result, then assert something.&lt;/p&gt;  &lt;p&gt;Large portions of the Silverlight client are cross-compiled and I wanted to do the same with the relevant tests. On the .NET side, a demonstrative test looks like this:&lt;/p&gt;  &lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Fact]
public void Can_insert_async_and_get_sync()
{
    using (var server = GetNewServer(port, path))
    {
        var documentStore = new DocumentStore { Url = &amp;quot;http://localhost:&amp;quot; + port };
        documentStore.Initialize();

        var entity = new Company { Name = &amp;quot;Async Company&amp;quot; };
        using (var session = documentStore.OpenAsyncSession())
        {
            session.Store(entity);
            session.SaveChangesAsync().Wait();
        }

        using (var session = documentStore.OpenSession())
        {
            var company = session.Load&amp;lt;Company&amp;gt;(entity.Id); // the SL client won’t have sync methods!

            Assert.Equal(&amp;quot;Async Company&amp;quot;, company.Name);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;The client is making use of Task from &lt;a title="The System.Threading.Tasks namespace provides types that simplify the work of writing concurrent and asynchronous code." href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.aspx" target="_blank"&gt;System.Threading.Tasks,&lt;/a&gt; and in case you didn’t know, this namespace has been ported to Silverlight as part of the &lt;a title="Visual Studio Async CTP" href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=18712f38-fcd2-4e9f-9028-8373dc5732b2&amp;amp;displaylang=en" target="_blank"&gt;CTP for the new C# 5 async syntax&lt;/a&gt;.The idea here is to make the async code read synchronously. &lt;/p&gt;

&lt;p&gt;Using &lt;a href="http://staxmanade.blogspot.com/2009/02/xunit-light-for-silverlight.html" target="_blank"&gt;XunitLight&lt;/a&gt;, I was able to cross compile a similar test and run it with the &lt;a title="The Microsoft Silverlight Unit Test Framework is a simple, extensible unit testing solution for Silverlight developers." href="http://code.msdn.microsoft.com/silverlightut" target="_blank"&gt;Silverlight Unit Test Framework&lt;/a&gt;. Only, it didn’t work.&lt;/p&gt;

&lt;p&gt;It doesn’t work because the test is running on the UI thread, and the call to Wait() blocks the execution on the current thread while the Task returned from SaveChangesAsync() executes. This task is making use of WebRequest and deep in the bowels of Silverlight some calls are being marshaled back onto the UI thread. Only that thread is being blocked by Wait(), so nothing happens.&lt;/p&gt;

&lt;h3&gt;The Standard Solution&lt;/h3&gt;

&lt;p&gt;The Silverlight Unit Test Framework has some infrastructure for handling this sort of problem. Jeff Wilcox, who built the framework, talks about asynchronous test support in &lt;a title="Asynchronous test support – Silverlight unit test framework and the UI thread" href="http://www.jeff.wilcox.name/2009/03/asynchronous-testing/" target="_blank"&gt;this post&lt;/a&gt;. Using the standard approach, I ended up with this test:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Asynchronous]
[TestMethod]
public void Can_insert_async_and_load_async()
{
    var documentStore = new DocumentStore { Url = &amp;quot;http://localhost:&amp;quot; + port };
    documentStore.Initialize();

    var entity = new Company { Name = &amp;quot;Async Company #1&amp;quot; };
    using (var session_for_storing = documentStore.OpenAsyncSession())
    {
        session_for_storing.Store(entity);
        var result = session_for_storing.SaveChangesAsync();
        EnqueueConditional(() =&amp;gt; result.IsCompleted || result.IsFaulted);
    }

    EnqueueCallback(() =&amp;gt;
    {
        using (var session_for_loading = documentStore.OpenAsyncSession())
        {
            var task = session_for_loading.LoadAsync&amp;lt;Company&amp;gt;(entity.Id);
            EnqueueConditional(() =&amp;gt; task.IsCompleted || task.IsFaulted);
            EnqueueCallback(() =&amp;gt; 
            {
                Assert.Equal(entity.Name, task.Result.Name);
                EnqueueTestComplete();
            });
        }
    });
}&lt;/pre&gt;

&lt;p&gt;The Asynchronous attribute tells the framework to use a queuing mechanism to execute the test. Then in your test, you must carefully arrange the code with various enqueue methods. This was actually one of the simpler tests, a couple of them had even more nesting of EnqueueCallback. It was functional, but my heart hurt.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I should also note that the code you see here is a mix of several things. From the Silverlight Unit Test Framework itself we have [Asynchronous] and the enqueue methods. (These methods are provided on a base class SilverlightTest). In addition, [TestMethod] is part of the Visual Studio Team Test (VSTT). In my .NET example above, I was using [Fact] from XUnit. The Silverlight Unit Test Framework includes a default provider for VSTT. Finally, the Assert.Equal call is from XUnit (well, from XunitLight).&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;The Alternative Solution&lt;/h3&gt;

&lt;p&gt;Writing the tests like this was killing me. So I lifted the syntax used in &lt;a title="free WPF and Silverlight from the stone" href="http://www.codeplex.com/caliburn"&gt;Caliburn&lt;/a&gt; for coroutines and I was able to convert the test to this:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Asynchronous]
[TestMethod]
public IEnumerable&amp;lt;Task&amp;gt; Can_insert_async_and_load_async()
{
    var documentStore = new DocumentStore { Url = &amp;quot;http://localhost:&amp;quot; + port };
    documentStore.Initialize();

    var entity = new Company {Name = &amp;quot;Async Company #1&amp;quot;};
    using (var session_for_storing = documentStore.OpenAsyncSession(dbname))
    {
        session_for_storing.Store(entity);
        yield return session_for_storing.SaveChangesAsync();
    }

    using (var session_for_loading = documentStore.OpenAsyncSession(dbname))
    {
        var task = session_for_loading.LoadAsync&amp;lt;Company&amp;gt;(entity.Id);
        yield return task;

        Assert.Equal(entity.Name, task.Result.Name);
    }
}&lt;/pre&gt;

&lt;h3&gt;How This Works&lt;/h3&gt;

&lt;p&gt;I’m leveraging the fact that all of the asynchronous work is performed with &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank"&gt;Task&lt;/a&gt;. In Caliburn, we use &lt;a title="IResult and Coroutines" href="http://caliburnmicro.codeplex.com/wikipage?title=IResult%20and%20Coroutines&amp;amp;referringTitle=Documentation" target="_blank"&gt;IResult&lt;/a&gt; for the same purpose. You’ll note that my test returns an IEnumerable of Task. I took the default implementation of the provider for VSTT, and I found the bit where the test was actually invoked and I changed it to this (note that &lt;em&gt;methodInfo&lt;/em&gt; contains the test method):&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public virtual void Invoke(object instance)
{
    var type = typeof (IEnumerable&amp;lt;&amp;gt;).MakeGenericType(new[] {typeof(Task)});
    if(type.IsAssignableFrom(methodInfo.ReturnType))
    {
        var executor = instance.GetType().GetMethod(&amp;quot;ExecuteTest&amp;quot;);
        executor.Invoke(instance, new[] {methodInfo});
    } else
    {
        methodInfo.Invoke(instance, None); // this is the original implementation
    }
}&lt;/pre&gt;

&lt;p&gt;I check to see if my test method returns an IEnumerable&amp;lt;T&amp;gt; and if it does, I then look for a method named ExecuteTest on my test class and I invoke that passing in my actual test method as a parameter.&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public void ExecuteTest(MethodInfo test)
{
    var tasks = (IEnumerable&amp;lt;Task&amp;gt;)test.Invoke(this, new object[] { });
    IEnumerator&amp;lt;Task&amp;gt; enumerator = tasks.GetEnumerator();
    ExecuteTestStep(enumerator);
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Yes, this code is far from bullet proof. It should check to make sure our test class contains an ExecuteTest method (among other things).&lt;/em&gt; &lt;/p&gt;

&lt;p&gt;Finally, ExecuteTestStep takes each of the Task instances that are yielded and calls the various enqueue methods from SilverlightTest.&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;private void ExecuteTestStep(IEnumerator&amp;lt;Task&amp;gt; enumerator)
{
    bool moveNextSucceeded = false;
    try
    {
        moveNextSucceeded = enumerator.MoveNext();
    }
    catch (Exception ex)
    {
        EnqueueTestComplete();
        return;
    }

    if (moveNextSucceeded)
    {
        try
        {
            Task next = enumerator.Current;
            EnqueueConditional(() =&amp;gt; next.IsCompleted || next.IsFaulted);
            EnqueueCallback(() =&amp;gt; ExecuteTestStep(enumerator));
        }
        catch (Exception ex)
        {
            EnqueueTestComplete();
            return;
        }
    }
    else EnqueueTestComplete();
}&lt;/pre&gt;

&lt;p&gt;If you are familiar with the source from Caliburn Micro, you’ll notice that this is very similar to the logic for executing IResult instances.&lt;/p&gt;

&lt;p&gt;The complete source, along with a few examples tests, is &lt;a title="Raven-Custom-Silverlight-Unit-Test-Provider" href="https://github.com/bennage/Raven-Custom-Silverlight-Unit-Test-Provider" target="_blank"&gt;available on github&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;I’ll likely improve it during the next couple of weeks. For example, there’s no real needs for the attributes when the method returns IEnumerable&amp;lt;Task&amp;gt;.&lt;/p&gt;

&lt;p&gt;Feedback is welcome.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=64651" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Reflection/default.aspx">Reflection</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Silverlight/default.aspx">Silverlight</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Caliburn/default.aspx">Caliburn</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/SoYouDontHaveToHurt/default.aspx">SoYouDontHaveToHurt</category></item><item><title>Testing Bindings In WPF</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2009/02/19/testing-bindings-in-wpf.aspx</link><pubDate>Fri, 20 Feb 2009 03:56:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:44397</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>4</slash:comments><description>&lt;p&gt;I was inspired to get off my duff and blog today by &lt;a title="seriously, it&amp;#39;s voyeurism" href="http://twitter.com/shanselman/statuses/1228349932" target="_blank"&gt;a tweet from Scott Hanselman&lt;/a&gt;. I didn’t really dig into the context of his tweet, but it was about TDD and WPF. In case you haven’t figured it out, I’m a big fan of WPF and TDD. Luckily, I’ve had the opportunity to work on a number of varied WPF projects (most using TDD) over the last couple of years. One problem I experienced over and over was incorrect bindings in my Xaml (as I alluded to in &lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2009/01/19/ui-patterns-for-wpf.aspx" target="_blank"&gt;this post&lt;/a&gt;). Binding errors are silent. They sneak up on you ninja-like. If you are keeping an eye on your Output window you can catch them, but it is very easy for them to just slip by.&lt;/p&gt;  &lt;p&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;margin-left:0px;border-top:0px;margin-right:0px;border-right:0px;" title="Karate Lessons" border="0" alt="Karate Lessons" align="right" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/iStock_5F00_000004919619XSmall_5F00_18DE0A5B.jpg" width="240" height="159" /&gt;About two years ago, Rob and I were working on a student records application for the &lt;a href="http://music.fsu.edu/" target="_blank"&gt;FSU College of Music&lt;/a&gt;. The system handled the entire lifecycle of a student, from application to graduation, and that involved lots of data. We had a number of screens in the app that were merely large data entry screens. Binding errors where a problem, and it seemed like a new batch showed up every time we made a release to the users.&lt;/p&gt;  &lt;p&gt;The errors might have been the result of renaming a bound property, bad spelling, or some other such silliness. They were easy mistakes to make and thus I began to think that we really needed a way to automatically test them.&lt;/p&gt;  &lt;p&gt;Well, I’m lazy and time passed (maybe a year) and then I mentioned it again to Rob. The next day he committed a prototype to the &lt;a title="free WPF and Silverlight from the stone" href="http://www.codeplex.com/caliburn"&gt;Caliburn&lt;/a&gt; trunk. (&lt;a title="No, Ayende and Rob are not Jesus, but I couldn&amp;#39;t resist the allusion." href="http://www.youtube.com/watch?v=jQcNiD0Z3MU" target="_blank"&gt;He’s like my own personal Ayende&lt;/a&gt;.)&lt;/p&gt;  &lt;p&gt;Here’s an example test copied directly from Caliburn’s &lt;a href="http://www.codeplex.com/caliburn/Wiki/View.aspx?title=Unit%20Testing%20Data%20Bindings&amp;amp;referringTitle=Table%20Of%20Contents" target="_blank"&gt;documentation&lt;/a&gt;:&lt;/p&gt;  &lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public class TestBase
{
    static TestBase()
    {
        var app = new MyApplication();
        app.InitializeComponent();
    }
}&lt;/pre&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class TestCase : TestBase
{
    [Test]
    public void Test()
    {
        var validator = Validator.For&amp;lt;MyUserControl, MyModel&amp;gt;();
        var result = validator.Validate();

        Assert.That(result.HasErrors, Is.False, result.ErrorSummary);
    }
}&lt;/pre&gt;

&lt;p&gt;In TestBase, we initialize the actual application so that we have access to application level resources. We need to this in a static constructor because we don’t want more than one instance of the application in the AppDomain. &lt;/p&gt;

&lt;p&gt;Now, check out the Test() method. The static class Validator.For&amp;lt;T,K&amp;gt;() method returns an instance of BindingValidator&amp;lt;K&amp;gt;. The type T is some FrameworkElement that contains the bindings we’re interested in and K is the type that the FrameworkElement is bound to. Calling the Validate() method causes Caliburn to instantiate T, crawl it’s tree, and collect all the bindings. It then compares those bindings to the type K to see if they are valid. Validate() actually returns an instance of ValidationResult&amp;lt;K&amp;gt;, which is a summary of everything that Caliburn found while comparing the bindings against the actual type T. &lt;/p&gt;

&lt;p&gt;The assertion in the test means that we expect Caliburn to find no errors, and if it does to provide us the summary. This is useful because there might be a number of binding errors and the ErrorSummary will give us the whole list.&lt;/p&gt;

&lt;p&gt;At this point, I’m just repeat what’s stated in Caliburn’s documentation. &lt;a title="you know you want it!" href="http://nhprof.com/" target="_blank"&gt;NH Prof&lt;/a&gt; was the first project where we’ve actually used the Testability features of Caliburn. Let’s check out a real live test from it:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class MessageBoxViewTextFixture : ViewTestFixtureBase
{
    private readonly ValidationResult&amp;lt;MessagePresenter&amp;gt; bindings;

    public MessageBoxViewTextFixture()
    {
        bindings = Validator.For&amp;lt;MessageBoxView, MessagePresenter&amp;gt;()
            .Validate();
    }

    [Test]
    public void BindingsDoNotHaveErrors()
    {
        Assert.That(bindings.HasErrors, Is.False, bindings.ErrorSummary);
    }

    [Test]
    public void MessageIsBound()
    {
        Assert.That(bindings.WasBoundTo(x =&amp;gt; x.Message));
    }
}&lt;/pre&gt;

&lt;p&gt;This test is for the view that displays a simple popup message. We have a simple presenter that backs the view and it has a message to display in its property Message. It’s tested independent of the view. (This is nice because we have a case in NH Prof where a single presenter might be bound to multiple views.)&lt;/p&gt;

&lt;p&gt;The ViewTestFixtureBase is identical to TestBase from the example above. Since it’s expensive to have Caliburn instantiate and crawl the UI validating the bindings, we only want to do this once. (I’m not really sure why I used the constructor, instead of [TestFixtureSetUp], but I did.) &lt;/p&gt;

&lt;p&gt;The first test covers 90% of what you typically need, catching spelling errors, etc. The second test however explicitly checks to see if we are bound to the Message property on the presenter. This is useful because that’s the core reason for this view. There may be other properties bound, but this is the one we definitely care about. (I think this affords liberty to designers while ensuring that a view delivers the business value that was intended.)&lt;/p&gt;

&lt;p&gt;Now, let’s pretend that I have a bad binding in my markup. Here’s the core snippet for the view used in the test above, MessageBoxView:&lt;/p&gt;

&lt;pre class="xml:nogutter:nocontrols" name="code"&gt;&amp;lt;Grid MaxWidth=&amp;quot;260&amp;quot;&amp;gt;
    &amp;lt;StackPanel&amp;gt;
        &amp;lt;TextBlock Foreground=&amp;quot;{StaticResource Text}&amp;quot; 
                   FontSize=&amp;quot;14&amp;quot;
                   TextWrapping=&amp;quot;Wrap&amp;quot;
                   Text=&amp;quot;{Binding Messyage}&amp;quot; /&amp;gt;
        &amp;lt;Button Content=&amp;quot;OK&amp;quot;
                Margin=&amp;quot;4 8 4 4&amp;quot;
                HorizontalAlignment=&amp;quot;Center&amp;quot;
                IsCancel=&amp;quot;True&amp;quot; /&amp;gt;
    &amp;lt;/StackPanel&amp;gt;    
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;

&lt;p&gt;Oops, I misspelled Message in the binding! When I execute my tests, they both fail. The first because there is a binding error and the second because it can’t find Message. Here’s the actual exception from the first test:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;NUnit.Framework.AssertionException:&amp;#160;&amp;#160; [MessageBoxView.Grid.StackPanel.TextBlock] The property &amp;#39;Messyage&amp;#39; was not found on &amp;#39;MessagePresenter&amp;#39;. 
    &lt;br /&gt;&amp;#160; Expected: False 

    &lt;br /&gt;&amp;#160; But was:&amp;#160; True&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Notice that it actually gives you the path to the offending binding: &lt;em&gt;MessageBoxView.Grid.StackPanel.TextBlock&lt;/em&gt;. Now that’s just cool! Thanks Rob!&lt;/p&gt;

&lt;p&gt;I can’t explain how much pain it saves to be able to do this. If you are doing TDD with WPF, you really need to check this out.&lt;/p&gt;

&lt;p&gt;I’ll post over the weekend some tests that are a bit more BDD in their styles.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=44397" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/UI/default.aspx">UI</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/UI+Patterns/default.aspx">UI Patterns</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/XAML/default.aspx">XAML</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Caliburn/default.aspx">Caliburn</category></item><item><title>UI Patterns for WPF</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2009/01/19/ui-patterns-for-wpf.aspx</link><pubDate>Tue, 20 Jan 2009 03:19:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43807</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>16</slash:comments><description>&lt;p&gt;There’s a lot of &lt;a href="http://channel9.msdn.com/shows/Continuum/MVVM/"&gt;recent buzz&lt;/a&gt; about the &lt;em&gt;Model-View-ViewModel&lt;/em&gt; or &lt;em&gt;MVVM.&lt;/em&gt; (I pronounce it like it rhymes with &lt;em&gt;Auntie Em&lt;/em&gt;.) Rather timely for me as a lot of my thinking about implementing UI patterns in WPF has begun to coalesce.&lt;/p&gt;  &lt;p&gt;There’s has been a lot of thought given to UI patterns prior to the advent of WPF. Martin Fowler has a relatively &lt;a href="http://martinfowler.com/eaaDev/uiArchs.html"&gt;succinct historical overview&lt;/a&gt; of GUI architectures. I’d like to start here by discussing how these established patterns are mapped to WPF. After that, I’d like to explore how WPF allows us to improve on these patterns. We’re probably in for a series of posts here.&lt;/p&gt;  &lt;h2&gt;Why Patterns?&lt;/h2&gt;  &lt;p&gt;One guiding principle, both for testability’s sake as well as for myriad other reasons, is &lt;a href="http://martinfowler.com/eaaDev/SeparatedPresentation.html" target="_blank"&gt;Separated Presentation&lt;/a&gt;. This is a just a special case of the general principle &lt;a href="http://en.wikipedia.org/wiki/Separation_of_concerns" target="_blank"&gt;Separation of Concerns&lt;/a&gt;. We separate the concerns because they are easier to &lt;a title="this is my apology" href="http://devlicious.com/blogs/christopher_bennage/archive/2008/03/30/the-roots-of-best-practices.aspx"&gt;test, maintain, and extend&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Let’s assume that you buy into the value of testability. The next problem is that UI code is notoriously difficult to test. This is a product of the way UI frameworks generally work. The common solution is to push as much behavior as possible into &lt;a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object" target="_blank"&gt;Plain Old CLR Objects&lt;/a&gt; (POCO). In other words, if a class is tied to the UI framework, and thus is difficult to test, it should have as little logic in it as possible; instead that logic should be delegated to classes that are easier to test.&lt;/p&gt;  &lt;h2&gt;The Patterns&lt;/h2&gt;  &lt;p&gt;There are number of standard approaches, er, patterns, that have been recognized. My influences for interpreting&amp;#160; these patterns are Martin Fowler, Jeremy Miller, John Gossman, and Dan Crevier. &lt;/p&gt;  &lt;p&gt;&lt;a href="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/registration_5F00_233140DF.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;margin:0px;display:inline;border-top:0px;border-right:0px;" title="An example of the registration form" border="0" alt="An example of the registration form" align="right" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/registration_5F00_thumb_5F00_2978176D.png" width="400" height="179" /&gt;&lt;/a&gt;I want to show you have these patterns look in code, so let’s establish a quick (and highly contrived) scenario. We have a registration form that accepts an email address, a password, and a confirmation of the password. There’s a button to initiate the registration, but the form has to be in a valid state in order for the button to be enabled. The rules are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;The email address cannot be blank. &lt;/li&gt;    &lt;li&gt;The password cannot be blank. &lt;/li&gt;    &lt;li&gt;The confirmation must match the password. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now for the patterns…&lt;/p&gt;  &lt;h3&gt;The Autonomous View&lt;/h3&gt;  &lt;p&gt;This is what we don’t want to do, but usually do. All of the logic is in the code-behind. Very little is delegated out to other classes, and when it is, it is typically delegated to concrete types so that hard dependencies exist. It’s impossible to test with this pattern because it is impossible to&lt;em&gt; isolate the behavior&lt;/em&gt; that need to be tested. Here’s the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112128" target="_blank"&gt;xaml&lt;/a&gt; and the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112089" target="_blank"&gt;code-behind&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;Model-View-Presenter&lt;/h3&gt;  &lt;p&gt;I’ve used the term MVP a lot. (&lt;a title="the Most Value Professional or some such thing, not a UI pattern" href="http://devlicious.com/blogs/rob_eisenberg/archive/2009/01/01/mvp-goodness.aspx" target="_blank"&gt;Hey, I am one now&lt;/a&gt;!) Fowler has suggested that MVP subsumes two more specific patterns (and that the term MVP should be retired in favor of them). Both of the child patterns have the same elements: a model, a view, and a presenter. Generally, the model is data that you are interested in, the view renders the data on screen, and the presenter handles all the “presentation concerns”. What constitutes “presentation concerns” though is part of what distinguishes the two child patterns.&lt;/p&gt;  &lt;h4&gt;Supervising Controller&lt;/h4&gt;  &lt;p&gt;The first of the MVP patterns is the supervising controller, or supervising presenter. (The terms controller and presenter are somewhat ambiguous themselves and are frequently interchanged.) The&amp;#160; presenter in the supervising presenter pattern has properties that interact with the view through data binding. Frequently, you’ll have simple event handlers (e.g., the click event for a button) that merely call methods on the presenter. (There is an alternative to the event handlers, but I’ll get to that later.) &lt;/p&gt;  &lt;p&gt;This pattern is easy to test because the presenter has most of the behavior for the UI and it is POCO. The deficit is that the view still contains some logic in the form of bindings.&lt;/p&gt;  &lt;p&gt;Notice here that we’ve introduced bindings into the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112098" target="_blank"&gt;xaml&lt;/a&gt; and that there is almost nothing in the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112126" target="_blank"&gt;code-behind&lt;/a&gt;. The real behavior is here in the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112132" target="_blank"&gt;presenter&lt;/a&gt;.&lt;/p&gt;  &lt;h4&gt;Passive View&lt;/h4&gt;  &lt;p&gt;This flavor of MVP squeezes out the remaining behavior out of the view. With this pattern you define an interface for the view that the presenter operates against. The implementation of the view interface has to be very simple, you want the absolute bare minimum in the view. The view is passive because it doesn’t know or do anything. The presenter handles all of the logic and manipulates the view. In WPF, you’ll end up with more code in the code-behind (because you are implementing the interface), but you can avoid bindings. Why do you want to avoid bindings? Because they are harder to tests… &lt;em&gt;or are they? &lt;/em&gt;More on that later.&lt;/p&gt;  &lt;p&gt;Here’s the view’s &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112080" target="_blank"&gt;interface&lt;/a&gt;. Note that the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112138" target="_blank"&gt;code-behind&lt;/a&gt; is more involved, but the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112091" target="_blank"&gt;xaml&lt;/a&gt; no longer has bindings. Also, notice how the &lt;a href="http://www.codeplex.com/wpfpatterns/SourceControl/changeset/view/4380#112120" target="_blank"&gt;presenter&lt;/a&gt; has to know a lot more about the view.&lt;/p&gt;  &lt;h3&gt;A Warning&lt;/h3&gt;  &lt;p&gt;We all want patterns to be distinct and specific, but the reality is that they are blurry. Often you will be combining elements from various patterns in order to accomplish what you need to do. Don’t get hung up on implementing a pure pattern.&lt;/p&gt;  &lt;h3&gt;Presentation Model vs MVVM&lt;/h3&gt;  &lt;p&gt;Actually, I will pick up here next time. I need to give you a reason to come back, right? :-)&lt;/p&gt;  &lt;p&gt;If you are interested in the playing with the code examples, I’m posting it on &lt;a href="http://www.codeplex.com/wpfpatterns" target="_blank"&gt;CodePlex&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43807" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Design+Patterns/default.aspx">Design Patterns</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Software+Architecture/default.aspx">Software Architecture</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Best+Practices/default.aspx">Best Practices</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/UI+Patterns/default.aspx">UI Patterns</category></item><item><title>Building a WPF Application: Part 6</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2009/01/13/building-a-wpf-application-part-6.aspx</link><pubDate>Tue, 13 Jan 2009 05:29:21 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43729</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/pages/building-a-wpf-application-table-of-contents.aspx"&gt;&lt;em&gt;ChumChase Table of Contents&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I opened up the ChumChase code this evening with the sad realization that my last commits were on November 14th. Ouch. In reading over the code, something jumped out at me immediately. In the code-behind for Shell.xaml, I had a lot of logic that didn&amp;#39;t need to be there. It was clumsy and not tested, but at least I had left myself a comment to that effect.&lt;/p&gt;  &lt;p&gt;The code handled switching from the default view to the 3D view. If you don&amp;#39;t know what I&amp;#39;m talking about, go back and read the &lt;a href="http://devlicious.com/blogs/christopher_bennage/pages/building-a-wpf-application-table-of-contents.aspx"&gt;older posts&lt;/a&gt;. The important part of Shell.xaml looked like this:&lt;/p&gt;  &lt;pre class="xml:nogutter:nocontrols" name="code"&gt;&amp;lt;Grid&amp;gt;
    &amp;lt;ContentControl x:Name=&amp;quot;MainView&amp;quot; /&amp;gt;

    &amp;lt;Button Content=&amp;quot;Toggle View&amp;quot;
            VerticalAlignment=&amp;quot;Top&amp;quot;
            HorizontalAlignment=&amp;quot;Right&amp;quot;
            Click=&amp;quot;ToggleView_Click&amp;quot; /&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;

&lt;p&gt;and the handler for the click (along with a dependent method) looked like this:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;private void ToggleView_Click(object sender, RoutedEventArgs e)
{
    if (MainView.Content is DefaultFeedView)
    {
        SetView(new _2Don3DView());
    }
    else
    {
        SetView(new DefaultFeedView());
    }
}

private void SetView(IFeedView view)
{
    MainView.Content = view;
    view.RefreshButton.Click += Refresh_Click;
}&lt;/pre&gt;

&lt;p&gt;Yes, _2Don3DView is &lt;em&gt;not&lt;/em&gt; a good name. I&amp;#39;ll &lt;a title="I mean, I just couldn&amp;#39;t stop laughing..." href="http://www.hulu.com/watch/38477/saturday-night-live-update-thursday-fix-it-109"&gt;fix it&lt;/a&gt;. Aside from the appalling appellation, this code is not very WPF-ish. What is it doing anyway?&lt;/p&gt;

&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.aspx"&gt;ContentControl&lt;/a&gt; is really a place holder. It represents the area in the application&amp;#39;s shell where we want to stick the main content. In the handler, we check to see what is currently in the placeholder and we switch it out. Since each view had it&amp;#39;s own button for refreshing the feed we needed to wire it up each time we switched the view. (Remember this way is naughty-naughty.) Our views implemented IFeedView so we could access their respective Refresh buttons.&lt;/p&gt;

&lt;h4&gt;A More Excellent Way&lt;/h4&gt;

&lt;p&gt;My ApplicationController class should really be responsible for this behavior. In order to make that happen, I created a property on it called CurrentPresenter. This property is the presenter that will back the current view. (A &lt;em&gt;presenter&lt;/em&gt; is a class that contains the logic for a portion of the UI, the corresponding &lt;em&gt;view&lt;/em&gt; is the visual part used to render that presenter.) Since the data context for Shell.xaml is already set to an instance of ApplicationController (it&amp;#39;s named _controller in the code-behind), I was able to changed the markup to look like this:&lt;/p&gt;

&lt;pre class="xml:nogutter:nocontrols" name="code"&gt;&amp;lt;Grid&amp;gt;
    &amp;lt;ContentControl Content=&amp;quot;{Binding CurrentPresenter}&amp;quot; /&amp;gt;

    &amp;lt;Button Content=&amp;quot;Toggle View&amp;quot;
            VerticalAlignment=&amp;quot;Top&amp;quot;
            HorizontalAlignment=&amp;quot;Right&amp;quot;
            Click=&amp;quot;ToggleView_Click&amp;quot; /&amp;gt;
&amp;lt;/Grid&amp;gt;&lt;/pre&gt;

&lt;p&gt;and then the event handler to this:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;private void ToggleView_Click(object sender, RoutedEventArgs e)
{
    _controller.ToggleView();
}&lt;/pre&gt;

&lt;p&gt;And now, let&amp;#39;s examine the tests for the desired behavior. I wanted ToggleView to alternate between an instance of DefaultFeedPresenter and an instance of _2Don3DPresenter. (Bad Christopher, bad!) I did not want ToggleView to create new instances, but to reuse existing ones.&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class The_application_controller
{
    [SetUp]
    public void given_a_context_of()
    {
        // stuff omitted for brevity //
        _controller = new ApplicationController();
    }

    [Test]
    public void raises_change_notification()
    {
        _controller
            .AssertThatAllProperties()
            .RaiseChangeNotification();
    }

    [Test]
    public void uses_the_expected_presenter_by_default()
    {
        Assert.That(_controller.CurrentPresenter, Is.InstanceOfType(typeof(DefaultFeedPresenter)));
    }

    [Test]
    public void toggles_to_the_3D_view_when_the_default_is_current()
    {
        _controller.ToggleView();
        Assert.That(_controller.CurrentPresenter, Is.InstanceOfType(typeof(_2Don3DPresenter)));
    }

    [Test]
    public void toggles_to_the_default_when_the_3D_view_is_current()
    {
        var default_presenter = _controller.CurrentPresenter;
        _controller.CurrentPresenter = new _2Don3DPresenter(_controller);
        _controller.ToggleView();

        Assert.That(_controller.CurrentPresenter, Is.EqualTo(default_presenter));
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Ooo, hey, what&amp;#39;s that first test? That raises notification bit? Oh, that just some cool stuff in &lt;/em&gt;&lt;a href="http://www.codeplex.com/caliburn"&gt;&lt;em&gt;Caliburn&lt;/em&gt;&lt;/a&gt;&lt;em&gt;, you can read more about that &lt;/em&gt;&lt;a href="http://www.codeplex.com/caliburn/Wiki/View.aspx?title=Unit%20Testing%20Property%20Change%20Notification&amp;amp;referringTitle=Table%20Of%20Contents"&gt;&lt;em&gt;here&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I added the following lines to ApplicationController in order to pass these tests:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;private readonly IList&amp;lt;IPresenter&amp;gt; _presenters = new List&amp;lt;IPresenter&amp;gt;();
private IPresenter _currentPresenter;

public IPresenter CurrentPresenter
{
    get { return _currentPresenter; }
    set
    {
        _currentPresenter = value;
        RaisePropertyChanged(&amp;quot;CurrentPresenter&amp;quot;);
    }
}

public void ToggleView()
{
    CurrentPresenter = (CurrentPresenter is DefaultFeedPresenter)
        ? _presenters[1]
        : _presenters[0];
}&lt;/pre&gt;

&lt;p&gt;I initialized _presenters in the constructor for ApplicationController with the instances of the presenters. (I was tempted here to introduce an IoC container, but I didn&amp;#39;t. We&amp;#39;ll talk more about that later.)&lt;/p&gt;

&lt;p&gt;So now, when ToggleView is called, the CurrentPresenter property is updated and change notification is raised, but what happens in the UI? How does it render the presenter instances? Well, given the markup from Shell.xaml we listed above, it doesn&amp;#39;t do anything.&lt;/p&gt;

&lt;h4&gt;I Love DataTemplates So Much, Why Don&amp;#39;t I Marry Them?&lt;/h4&gt;

&lt;p&gt;We need to tell WPF how to render each presenter. We already have user controls that define each view. We can reuse those. I added the following to the Grid containing my ContentControl:&lt;/p&gt;

&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;&amp;lt;Grid.Resources&amp;gt;
    &amp;lt;DataTemplate DataType=&amp;quot;{x:Type Model:DefaultFeedPresenter}&amp;quot;&amp;gt;
        &amp;lt;Views:DefaultFeedView /&amp;gt;
    &amp;lt;/DataTemplate&amp;gt;
    &amp;lt;DataTemplate DataType=&amp;quot;{x:Type Model:_2Don3DPresenter}&amp;quot;&amp;gt;
        &amp;lt;Views:_2Don3DView /&amp;gt;
    &amp;lt;/DataTemplate&amp;gt;
&amp;lt;/Grid.Resources&amp;gt;&lt;/pre&gt;

&lt;p&gt;The DataType property tells WPF that anything bound to an instance of the given type should use the template. Since I placed these in the resources for the grid, it will affect any bindings inside the grid. Each data template simply contains the corresponding user control. I could have inlined the user controls, but I already had tests in place and I believe this makes the markup easier to read.&lt;/p&gt;

&lt;p&gt;In making these changes, I did break something. Something that was not being tested... but it&amp;#39;s time for bed so I&amp;#39;ll leave that for another night. &lt;/p&gt;

&lt;p&gt;More to come!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43729" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Design+Patterns/default.aspx">Design Patterns</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/DataBinding/default.aspx">DataBinding</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/data+binding/default.aspx">data binding</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ChumChase/default.aspx">ChumChase</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/data+templates/default.aspx">data templates</category></item><item><title>TDD Firestarter in Tampa</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2009/01/07/tdd-firestarter-in-tampa.aspx</link><pubDate>Wed, 07 Jan 2009 22:12:10 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43668</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>2</slash:comments><description>&lt;p&gt;The new year has already gotten away from me and it&amp;#39;s only 7 days old. (&lt;a title="We watch a lot of Rankin\Bass over the holidays." href="http://en.wikipedia.org/wiki/Rudolph&amp;#39;s_Shiny_New_Year"&gt;Come back, Baby Happy!&lt;/a&gt;)&lt;/p&gt;  &lt;p&gt;&lt;b&gt;&lt;a href="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/iStock_5F00_000000370181XSmall12_5F00_00046DA5.jpg"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;margin-left:0px;border-top:0px;margin-right:0px;border-right:0px;" border="0" alt="strike a match" align="right" src="http://devlicious.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/christopher_5F00_bennage/iStock_5F00_000000370181XSmall12_5F00_thumb_5F00_6B9EA819.jpg" width="300" height="220" /&gt;&lt;/a&gt;&lt;/b&gt;In less than 2 weeks from now, we&amp;#39;re going to a have full day of TDD in Tampa, FL. The event is designed so that everyone will find value, whether you are merely curious about methodology or a veteran practitioner.&lt;/p&gt;  &lt;p&gt;We&amp;#39;re starting off the day with introductory and intermediate session on TDD and following it up with some very focused sessions in the afternoon. (I&amp;#39;m going to be talking about doing TDD with WPF and I&amp;#39;ll be using a little bit o&amp;#39; &lt;a title="ye olde Caliburn, freed from the stone" href="http://www.codeplex.com/caliburn"&gt;Caliburn&lt;/a&gt; as well.)&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Saturday, January 17, 2009&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;&lt;b&gt;9:00 AM–5:00PM&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;&lt;b&gt;&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032397083&amp;amp;culture=en-US"&gt;Click here to register&lt;/a&gt; or call (877) 673-8368 with event ID 1032397083&lt;strong&gt;.&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Speakers include &lt;a href="http://www.cornetdesign.com/"&gt;Cory Foy&lt;/a&gt;, &lt;a href="http://scottcreynolds.lostechies.com/"&gt;Scott C. Reynolds&lt;/a&gt;, &lt;a href="http://schambers.lostechies.com/"&gt;Sean Chambers&lt;/a&gt;, and &lt;a href="http://devlicio.us/blogs/rob_eisenberg"&gt;Rob Eisenberg&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Please come out and join us! Did I mention it&amp;#39;s &lt;em&gt;free&lt;/em&gt;?&lt;/p&gt;  &lt;p&gt;More information &lt;a title="but haven&amp;#39;t I told you everyting that&amp;#39;s important?" href="http://tddfirestarter.lostechies.com/blogs/news/archive/2008/12/08/tdd-firestarter-conference-information-and-registration.aspx"&gt;here&lt;/a&gt;...&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43668" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Presentations/default.aspx">Presentations</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Events/default.aspx">Events</category></item><item><title>Unit Testing Change Notification</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/11/13/unit-testing-change-notification.aspx</link><pubDate>Thu, 13 Nov 2008 20:43:05 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:43034</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>11</slash:comments><description>&lt;p&gt;In WPF work, it is very common to work with implementations of &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx" target="_blank"&gt;INotifyPropertyChanged&lt;/a&gt;. We need support for change notification in order to bind to the UI, and this interface is frequently the best approach. This means I have lots of properties that look like this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public string FirstName
{
    get { return _firstName;}
    set
    {
        _firstName = value;
        RaisePropertyChanged(&amp;quot;FirstName&amp;quot;);
    }
}&lt;/pre&gt;
&lt;p&gt;I&amp;#39;ve gone back and forth as to whether or not I should test these properties for change notification on properties.&amp;nbsp; My main argument for not doing it, is the ROI. The typical test pattern might look something like this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Test]
public void FirstName_raises_change_notification()
{
    bool has_property_changed = false;
    _person.PropertyChanged += 
        (s, e) =&amp;gt; { if (e.PropertyName == &amp;quot;FirstName&amp;quot;) has_property_changed = true; };
    _person.FirstName = &amp;quot;new_name&amp;quot;;

    Assert.That(has_property_changed);
}&lt;/pre&gt;
&lt;p&gt;Sure, this isn&amp;#39;t a long test, but when you consider the number of properties I could be dealing with you&amp;#39;ll see the potential for a lot of noise.&lt;/p&gt;
&lt;p&gt;I also don&amp;#39;t like the fact that I have &lt;em&gt;yet another string&lt;/em&gt; in my code; easy to miss when refactoring. Nevertheless, I feel like I &lt;em&gt;ought&lt;/em&gt; to have test coverage for these change notifications.&lt;/p&gt;
&lt;p&gt;What&amp;#39;s the solution? Make change notification easier to test.&lt;/p&gt;
&lt;h3&gt;Step One&lt;/h3&gt;
&lt;p&gt;I extracted out the test pattern into an extension method that applies to INotifyPropertyChanged. So my test now looks like this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Test]
public void FirstName_raises_change_notification()
{
    _person.AssertThatPropertyRaisesChangeNotification(
        () =&amp;gt; _person.FirstName);
}&lt;/pre&gt;
&lt;p&gt;By using an expression to identify the property, I removed the magic string. I also have an overload if I need to set the property to a specific value:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Test]
public void FirstName_raises_change_notification()
{
    _person.AssertThatPropertyRaisesChangeNotification(
        () =&amp;gt; _person.FirstName, &amp;quot;new_name&amp;quot;);
}&lt;/pre&gt;
&lt;p&gt;The code for the extension is this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public static class AssertExtensions
{
    public static void AssertThatPropertyRaisesChangeNotification&amp;lt;T, K&amp;gt;(
        this T propertyOwner,
        Expression&amp;lt;Func&amp;lt;K&amp;gt;&amp;gt; property,
        K valueToSet) where T : INotifyPropertyChanged
    {
        var has_property_changed = false;

        var memberExpression = (MemberExpression) property.Body;
        var propertyInfo = (PropertyInfo) memberExpression.Member;

        propertyOwner.PropertyChanged +=
            (s, e) =&amp;gt; { if (e.PropertyName == propertyInfo.Name) has_property_changed = true; };

        propertyInfo.SetValue(propertyOwner, valueToSet, null);

        if (has_property_changed) return;

        var msg =
            string.Format(
                &amp;quot;The property, {0}, did not raise change notification.\n&amp;quot; +
                &amp;quot;The property was set to &amp;#39;{1}&amp;#39;.\nThe property is owned by {2}&amp;quot;,
                propertyInfo.Name,
                valueToSet,
                typeof (T).Name);

        throw new AssertionException(msg);
    }

    public static void AssertThatPropertyRaisesChangeNotification&amp;lt;T, K&amp;gt;(
        this T propertyOwner,
        Expression&amp;lt;Func&amp;lt;K&amp;gt;&amp;gt; property) where T : INotifyPropertyChanged
    {
        propertyOwner.AssertThatPropertyRaisesChangeNotification(property, default(K));
    }
}&lt;/pre&gt;
&lt;h3&gt;Step Two&lt;/h3&gt;
&lt;p&gt;The next step (which I haven&amp;#39;t done &lt;em&gt;yet&lt;/em&gt;) would be to provide a fluent API for easily expressing which classes and properties I care about. With the extension above, I&amp;#39;m still just dealing with one property at a time. &lt;/p&gt;
&lt;p&gt;What I would like is a way to say &amp;quot;all public properties on class X, except Y &amp;amp; Z&amp;quot; or perhaps &amp;quot;only properties Y &amp;amp; Z on class X&amp;quot;. Then I can have concise, descriptive, intent-revealing tests regarding change notification.&lt;/p&gt;
&lt;p&gt;Thoughts? Improvements?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=43034" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/lambdas/default.aspx">lambdas</category></item><item><title>Solving Problems with TDD</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/11/06/solving-problems-with-tdd.aspx</link><pubDate>Thu, 06 Nov 2008 20:03:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:42921</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>7</slash:comments><description>&lt;p&gt;I&amp;#39;m giving a talk on TDD at our local UG tonight, and under the influence of some recent posts here on devlicio.us, I just finished reworking my presentation. This post is an outline for the first half of my presentation.&lt;/p&gt; &lt;h3&gt;The Problems&lt;/h3&gt; &lt;p&gt;Code has entropy. That is over time it deteriorates. At least, that&amp;#39;s the metaphor we developers like to use. What is really means is that the code becomes harder to maintain and extend as it is maintained and extended over time. Did you follow that? Our typical approach to maintaining and extending code causes the code to become fragile and rigid and thus harder to maintain and extend in the future.&lt;/p&gt; &lt;p&gt;There are three common difficulties that arise, maybe more, but I&amp;#39;m focusing on three:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Unchangeable Code&lt;/li&gt; &lt;li&gt;Unintelligible Code&lt;/li&gt; &lt;li&gt;Unnecessary Code&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;A portion of code becomes unchangeable when its deeply entwined and entangled with other portions of code that have different responsibilities. You can&amp;#39;t change method X because we really don&amp;#39;t know what that will do to Y and Z.&lt;/p&gt; &lt;p&gt;Code can become unintelligible for lots of reasons: abbreviated names, circuitous logic, enormous methods, confusion of responsibilities, use of php☺, etc.&lt;/p&gt; &lt;p&gt;Finally, unnecessary code is code that is not used by the system. It can be vestigial, or as often happens, it can be the result of feature anticipation. &lt;em&gt;We thought this was going to be needed in the app, so...&lt;/em&gt;&lt;/p&gt; &lt;h3&gt;The Solutions&lt;/h3&gt; &lt;p&gt;There are some generally accepted solutions to these three problems.&lt;/p&gt; &lt;p&gt;In the case of unchangeable code, we can apply such patterns as &lt;a href="http://en.wikipedia.org/wiki/Separation_of_concerns" target="_blank"&gt;Separation of Concerns&lt;/a&gt; (SoC) and the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank"&gt;Single Responsibility Principle&lt;/a&gt; (SRP). For addressing unintelligible code, we have a number of techniques such as &lt;em&gt;thoughtful&lt;/em&gt; comments, explicit naming, SRP again, etc. Finally, for unnecessary code we have the old axiom of &lt;a href="http://en.wikipedia.org/wiki/YAGNI" target="_blank"&gt;You Ain&amp;#39;t Gonna Need It.&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Okay, so we know how to solve the problems. Or least, we know how to mediate them. So what? What does that have to do with TDD?&lt;/p&gt; &lt;p&gt;My proposition is this:&lt;strong&gt; solutions are without value unless they are applied&lt;/strong&gt;.&lt;/p&gt; &lt;p&gt;Additionally, when a problem occurs over time, the solution must be applied over time.&lt;/p&gt; &lt;h3&gt;The Analogy&lt;/h3&gt; &lt;p&gt;I just started going to the gym. It&amp;#39;s been about a decade since I did that, but I&amp;#39;m back. For the past several years however, I have been preaching to certain family members the value of exercise and healthy diet. I knew the benefits: stress reduction, longevity, improved sleeping, and just plain feeling better. However, I wasn&amp;#39;t really doing either.&lt;/p&gt; &lt;p&gt;I had the problem and I believed in the solution and, in fact, I made attempts to employ the solution. Ultimately, I was unsuccessful. That is, until I committed to go to the gym three days week at a set time and with a workout buddy.&lt;/p&gt; &lt;p&gt;My point is this, we are human beings and despite being smart we frequently revert to doing &amp;quot;the easiest thing&amp;quot;. Therefore, we ought to set up some sort of framework of methodology or discipline where the easiest thing is actually what we &lt;em&gt;want&lt;/em&gt; to do.&lt;/p&gt; &lt;p&gt;Additionally, I have to &lt;em&gt;keep on going&lt;/em&gt; to gym. For as long as I want to be fit, I will need to exercise. In the same way, for as long as I want my code to fit I will need to apply good principles.&lt;/p&gt; &lt;h3&gt;TDD as a Discipline&lt;/h3&gt; &lt;p&gt;I will argue that TDD is a discipline that enables the application of the solutions outlined above. Perhaps you apply those solution naturally. Perhaps you can benchmark 200lbs because of your genetic disposition. Bully for you. Go ahead and skip the rest.&lt;/p&gt; &lt;p&gt;Let&amp;#39;s examine a few essentials of TDD and see if they really address the problems we outlined.&lt;/p&gt; &lt;h4&gt;Test First&lt;/h4&gt; &lt;p&gt;I&amp;#39;m an advocate of automated testing in general. However, I do think that writing your tests first yields additional value. Primarily, it helps you &lt;em&gt;discover your ideal API&lt;/em&gt;. In other words, you can design your API up front such that it is more intuitive. More intuitive means easier to understand. &lt;/p&gt; &lt;p&gt;Secondly, testing first helps you identify dependencies early. You quickly discover that class X will need a Y and so you are forced to create seams in the application at the onset. This encourages SoC and SRP.&lt;/p&gt; &lt;h4&gt;Testing Units&lt;/h4&gt; &lt;p&gt;It took me a long time to understand the &amp;quot;unit&amp;quot; part of unit testing. The idea is that you decompose your problem into units, and deal with the problem one unit at a time. You could call this &amp;quot;test just one thing&amp;quot;. Okay, well what is &amp;quot;one thing&amp;quot;? That is hard to tell and comes with experience. Nevertheless, &lt;em&gt;the practice&lt;/em&gt; of trying to decompose a problem and identifying units leads you back to SoC and SRP again.&lt;/p&gt; &lt;h4&gt;Just Enough Code&lt;/h4&gt; &lt;p&gt;Another tenet of TDD is to &lt;em&gt;write only enough code to pass the test&lt;/em&gt;. Our natural instinct is to anticipate. It is part of what we are as developer, and it is not a bad thing. However, like many strengths, it can become a weakness. By constraining ourselves to a single problem at a time we will end up with less code. It also forces us to be conscious about our anticipation and to ask if a given scenario is &lt;em&gt;really&lt;/em&gt; necessary.&lt;/p&gt; &lt;h3&gt;Conclusion&lt;/h3&gt; &lt;p&gt;I know that there is much contention over the actual value of TDD as a practice, and I am not going to force it on anyone (unless I hire you and now you are warned). However, I have found it to be a useful discipline for helping me to overcome common problems and because of that I encourage it&amp;#39;s use.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=42921" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Design+Patterns/default.aspx">Design Patterns</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Agile/default.aspx">Agile</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Software+Architecture/default.aspx">Software Architecture</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ALT.NET/default.aspx">ALT.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Best+Practices/default.aspx">Best Practices</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Opinion/default.aspx">Opinion</category></item><item><title>Tricksy Dispatcher &amp; Running Tests in TDD.NET</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/10/23/tricksy-dispatcher-amp-running-tests-in-tdd-net.aspx</link><pubDate>Thu, 23 Oct 2008 15:42:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:42779</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>5</slash:comments><description>&lt;p&gt;&lt;em&gt;Updated 11/07/2008&lt;/em&gt;&lt;/p&gt; &lt;p&gt;I recently ran into an interesting situation. I had an &lt;a href="http://msdn.microsoft.com/en-us/library/ms668604.aspx" target="_blank"&gt;ObservableCollection&lt;/a&gt; bound to my UI in WPF, and I needed to updated this collection on something other than the UI thread. In other words, I was adding items to a UI-bound collection on a different thread, which triggered the change notification events on that non-UI thread. Unfortunately, you can&amp;#39;t do that, the change notification events for ObservableCollection can only be execute on the UI thread. &lt;/p&gt; &lt;p&gt;Karl Hulme &lt;a href="http://karlhulme.wordpress.com/2007/03/04/synchronizedobservablecollection-and-bindablecollection/" target="_blank"&gt;blogged about this&lt;/a&gt; and posted some custom collections he wrote to deal with the problem. Karl&amp;#39;s solution was heavier (and more generic than I needed), so I distilled his code down to this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public class BindableCollection&amp;lt;T&amp;gt; : ObservableCollection&amp;lt;T&amp;gt;
{
    private readonly Dispatcher _dispatcher;

    public BindableCollection(Dispatcher dispatcher)
    {
        if (dispatcher == null) throw new ArgumentNullException(&amp;quot;dispatcher&amp;quot;);

        _dispatcher = dispatcher;
    }

    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        _dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =&amp;gt; base.OnPropertyChanged(e)));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        _dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =&amp;gt; base.OnCollectionChanged(e)));
    }
}&lt;/pre&gt;
&lt;p&gt;This really a simplified version of what Karl did, but it was all I needed. When you instantiate this collection, you pass in the dispatcher for the UI. You can easily get that using &lt;a target="_blank"&gt;System.Windows.Threading.Dispatcher.CurrentDispatcher&lt;/a&gt;. In case you are not familiar with it, Dispatcher is WPF class for managing the queue of work items for a thread.&lt;/p&gt;
&lt;p&gt;It&amp;#39;s a sweet trick. To sum up, the collection is now dependent on a Dispatcher. We pass into it the Dispatcher for the UI thread. Then we override the change notification methods, so that we marshal the actual underlying change notification back onto the UI thread. &lt;/p&gt;
&lt;p&gt;The cast to an Action looks a bit weird, but unfortunately lambdas are not implicitly cast to Actions.&lt;/p&gt;
&lt;h3&gt;The Unexpected Bug&lt;/h3&gt;
&lt;p&gt;I guess all bugs are unexpected, so whatever.&lt;/p&gt;
&lt;p&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="240" alt="Notice the similarity in colors between Flash and Ayende&amp;#39;s blog? Coincidence?" src="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/WPFDispatcherRunningTestsinTDD.NET_9575/Flash207_3.jpg" width="170" align="right" border="0" /&gt; A few of our automated tests dealt with this new BindableCollection, and everything was green when I executed the tests through ReSharper&amp;#39;s test runner. Likewise, everything ran as expected in the application itself. However, when running these test through &lt;a href="http://www.testdriven.net/" target="_blank"&gt;TDD.NET&lt;/a&gt; the _dispatcher.Invoker call &lt;em&gt;never returned&lt;/em&gt;. &lt;/p&gt;
&lt;p&gt;Right now, it&amp;#39;s important to give credit where it is due. &lt;a href="http://ayende.com/Blog/" target="_blank"&gt;Ayende&lt;/a&gt; solved this problem before I had time to fully grasp it even. If there is a &lt;a href="http://en.wikipedia.org/wiki/Justice_League" target="_blank"&gt;Justice League&lt;/a&gt; of .NET, Ayende is &lt;a href="http://en.wikipedia.org/wiki/Wally_West" target="_blank"&gt;Flash&lt;/a&gt; (and &lt;em&gt;we think&lt;/em&gt;&amp;nbsp;&lt;a href="http://graysmatter.codivation.com/" target="_blank"&gt;Justice Gray&lt;/a&gt; is probably Superman? I mean, the hair, right?).&lt;/p&gt;
&lt;p&gt;Anyway, errors in this explanation are my own.&lt;/p&gt;
&lt;h3&gt;Diagnosis&lt;/h3&gt;
&lt;p&gt;When you call Invoke() the action is placed onto a queue. The&amp;nbsp; processing of the queue is triggered by the method WndProcHook(). This method is the hook for processing message from the OS.&amp;nbsp; In other words, the queue is only processed each time the window receives a message.&lt;/p&gt;
&lt;p&gt;Now TDD.NET executes tests in a console, ReSharper&amp;#39;s test execute in a GUI. So with TDD.NET, the queue is never processed and hence the Invoke method never returns.&lt;/p&gt;
&lt;h3&gt;The Revision&lt;/h3&gt;
&lt;p&gt;Ayende came up with the following revision to our collection. You can see some functional influence here:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public class BindableCollection&amp;lt;T&amp;gt; : ObservableCollection&amp;lt;T&amp;gt;
{
    private readonly Action&amp;lt;Action&amp;gt; _dispatcher;

    public BindableCollection(Action&amp;lt;Action&amp;gt; dispatcher)
    {
        if (dispatcher == null) throw new ArgumentNullException(&amp;quot;dispatcher&amp;quot;);

        _dispatcher = dispatcher;
    }

    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        _dispatcher(() =&amp;gt; base.OnPropertyChanged(e));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        _dispatcher(() =&amp;gt; base.OnCollectionChanged(e));
    }
}&lt;/pre&gt;
&lt;p&gt;Instantiating this, might look like this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;new BindableCollection&amp;lt;stuff&amp;gt;(action =&amp;gt; dispatcher.Invoke(DispatcherPriority.Normal, action));&lt;/pre&gt;
&lt;p&gt;However, in my tests, I can avoid the dispatcher altogether and simply:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;new BindableCollection&amp;lt;stuff&amp;gt;(action =&amp;gt; action());&lt;/pre&gt;
&lt;p&gt;Hope someone else finds this useful.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=42779" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Threading/default.aspx">Threading</category></item><item><title>Building a WPF Application: Part 3</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/08/20/building-a-wpf-application-part-3.aspx</link><pubDate>Wed, 20 Aug 2008 04:28:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:41939</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>8</slash:comments><description>&lt;a title="Table of Contents for ChumChase" href="http://devlicious.com/blogs/christopher_bennage/pages/building-a-wpf-application-table-of-contents.aspx" target="_blank"&gt;Table of Contents&lt;/a&gt;
&lt;h3&gt;Application Architecture&lt;/h3&gt; &lt;p&gt;I&amp;#39;m going to back up and bit discuss my overall approach to structuring this WPF project. So far the solution consists of four projects:&lt;/p&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="159" alt="solution" src="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildingaWPFApplicationPart4_150D4/solution_3.png" width="256" align="right" border="0" /&gt;  &lt;ul&gt; &lt;li&gt;&lt;strong&gt;ChumChase&lt;/strong&gt; is the actual WPF project.  &lt;li&gt;&lt;strong&gt;FriendFeed&lt;/strong&gt; is the official .NET api I downloaded from &lt;a href="http://code.google.com/p/friendfeed-api/downloads/list" target="_blank"&gt;here&lt;/a&gt;, and patched so that it would compile. :-)  &lt;li&gt;&lt;strong&gt;IntegrationTests&lt;/strong&gt; is for testing the bits of the application that interact with the FriendFeed api.&amp;nbsp; I separated this out because it is much slower to run than my &lt;strong&gt;Specifications&lt;/strong&gt; tests, and goes beyond the trust boundary of the app.  &lt;li&gt;&lt;strong&gt;Specifications&lt;/strong&gt; is the bulk of the unit tests for the project. I&amp;#39;m influenced by the whole &lt;a title="Does really know what BDD is? Does anybody really care?" href="http://en.wikipedia.org/wiki/Behavior_driven_development" target="_blank"&gt;BDD&lt;/a&gt; approach, and I like to think of my unit tests as &lt;em&gt;executable technical specifications&lt;/em&gt;. &lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;Project Structure&lt;/h3&gt; &lt;p&gt;&lt;strong&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildingaWPFApplicationPart4_150D4/project_2.png"&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="357" alt="project" src="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildingaWPFApplicationPart4_150D4/project_thumb.png" width="238" align="right" border="0" /&gt;&lt;/a&gt;&lt;/strong&gt;In the main project you&amp;#39;ll find the following:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Presenters&lt;/strong&gt; - This folder contains the presenter classes. I usually name these classes with the suffix &amp;quot;Presenter, though that&amp;#39;s a bit of a hang over from other frameworks (MonoRail, RoR). This directory is where I have the HomePresenter class we&amp;#39;ve been discussing.  &lt;li&gt;&lt;strong&gt;Views&lt;/strong&gt; - These are usually user controls or some derivative thereof. I name them to correspond to their presenter. So you would expect, since we have HomePresenter, to find HomeView.xaml. (Actually, I goofed and the current source has the view named HomeFeedView.xaml).  &lt;li&gt;&lt;strong&gt;Model&lt;/strong&gt; - This is the object model that represents the &amp;quot;business problem&amp;quot; I&amp;#39;m trying to solve. In this case it happens to mirror the actual api quite a bit.  &lt;li&gt;&lt;strong&gt;Repositories&lt;/strong&gt; - Here I am influenced by Eric Evans&amp;#39; &lt;a title="Sams Teach Yourself WPF in 24 Hours -- preorder yours today! :-)" href="http://www.amazon.com/Sams-Teach-Yourself-WPF-Hours/dp/0672329859" target="_blank"&gt;book&lt;/a&gt; on Domain-Driven Design. Repositories are classes that allow me to access/persist data in a way that makes sense to my business domain. It&amp;#39;s also a place where I can hook in orthogonal concerns such as logging, caching, or security. Repositories differ from the traditional data access layer in that there is an emphasis on the domain model (as opposed to following the semantics of a relation database).  &lt;li&gt;&lt;strong&gt;Services&lt;/strong&gt; - These are supporting classes. They are not necessarily part of the business or problem domain. A classic example is an SMTP provider. Classes in your model or presenters might utilize these.  &lt;li&gt;&lt;strong&gt;Framework&lt;/strong&gt; - These support the framework of application, but don&amp;#39;t have anything to do with the business concern. If we need to create a base class for views, we&amp;#39;d put it here. Currently, I have a class there that is going to assist us with binding to commands. This is code that could likely be pushed out to a reusable library.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Aside from these folders you will also find:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;App.xaml&lt;/strong&gt; - This is the starting point for the application. It will kick off our Windsor configuration, and launch the first window for the application. Eventually, we&amp;#39;ll include some application-wide resources in the xaml, primarily for styling.  &lt;li&gt;&lt;strong&gt;Shell.xaml&lt;/strong&gt; - This is the main window of the application. I call it Shell, because there is very little to its UI. It&amp;#39;s content is bound to view of our current presenter. This class might have some logic in it&amp;#39;s code-behind if we need to do some things like managing a set of tabs. It also provides the overall layout of the application.  &lt;li&gt;&lt;strong&gt;ApplicationController&lt;/strong&gt; - I briefly mentioned this in the last post. Honestly, I&amp;#39;ve waffled a bit on what to call it. It&amp;#39;s responsibility is to coordinate the presenters for the application. For example, if presenter X needs to load presenter Y it passes that request to the application controller. In this, it also handles some statefulness for the overall application. This will become more clear as we begin to work with the class.&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;What&amp;#39;s Not Here Yet&lt;/h3&gt; &lt;p&gt;There are several other things that usually appear in my projects. I often end up with a base class for test fixtures, though I think the new Rhino.Mocks features might affect that. However, the big piece that&amp;#39;s missing is the folders and files related to organizing the XAML.&lt;/p&gt; &lt;p&gt;It&amp;#39;s common for me to have the following:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Colors &amp;amp; Brushes&lt;/strong&gt; - I typically have a&amp;nbsp; resource dictionary dedicated to defining the colors and brushes used in the application.  &lt;li&gt;&lt;strong&gt;Default Styles&lt;/strong&gt; - When I provide a completely custom style for an application, I&amp;#39;ll have a resource dictionary that defines all of the default styles for controls. It useful to note that I avoid putting control templates inline in this dictionary.  &lt;li&gt;&lt;strong&gt;Control Templates folder&lt;/strong&gt; - In this folder, I will have a file for each control template in the application. I&amp;#39;ll usually have a &amp;quot;manifest&amp;quot; resource dictionary where I merge in all of the individual templates. This helps to keep the structure clean in other areas. These are the control templates that are referenced in my default styles dictionary.  &lt;li&gt;&lt;strong&gt;Data Templates folder&lt;/strong&gt; - Inside the Views directory, I will have a sub-folder for data templates. Data templates really are views.&lt;/li&gt;&lt;/ul&gt; &lt;h3&gt;What Happens at Runtime?&lt;/h3&gt; &lt;p&gt;A synopsis of what happens at runtime, well, what &lt;em&gt;will&lt;/em&gt; happen once we&amp;#39;ve finished:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;App.xaml starts off.&lt;/li&gt; &lt;li&gt;In its constructor, we configure our &lt;em&gt;container&lt;/em&gt;, which in this case is Windsor.&amp;nbsp; The container is told how to resolve resources, such as where do I find the actual implementation of IFriendFeedProxy.&lt;/li&gt; &lt;li&gt;Still in the constructor, we then request an instance of &lt;strong&gt;IApplicationController&lt;/strong&gt;, and call &lt;strong&gt;StartApplication()&lt;/strong&gt;.&amp;nbsp; Note that we don&amp;#39;t set the &lt;strong&gt;StartupUri&lt;/strong&gt; in the XAML for App.&lt;/li&gt; &lt;li&gt;&lt;strong&gt;StartApplication()&lt;/strong&gt; might handle some things like loading up user preferences, but mostly it will initialize and open Shell.xaml. &lt;/li&gt; &lt;li&gt;Somewhere around here we&amp;#39;ll request the HomePresenter from the container, and inject into the shell.&lt;/li&gt; &lt;li&gt;As the user interacts with the application, presenters may be removed and new ones injected (probably into a tab, or new window). The shell&amp;#39;s code-behind has the code for actually placing these presenter&amp;#39;s views into the layout.&lt;/li&gt; &lt;li&gt;The presenter will have use &lt;a target="_blank"&gt;commands&lt;/a&gt; as properties that can be bound to in there views. These commands are coordinators of individual activities in the application.&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I&amp;#39;m certain that parts of this are confusion, but I believe it will make sense as we continue to build the application. As always, your feedback is welcome.&lt;/p&gt; &lt;p&gt;More to come!&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2008/11/07/building-a-wpf-application-part-4.aspx"&gt;Continue to Part 4.&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=41939" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Software+Architecture/default.aspx">Software Architecture</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ChumChase/default.aspx">ChumChase</category></item><item><title>Building a WPF Application: Part 2</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/08/16/building-a-wpf-application-part-2.aspx</link><pubDate>Sun, 17 Aug 2008 01:34:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:41865</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>5</slash:comments><description>&lt;a title="Table of Contents for ChumChase" href="http://devlicious.com/blogs/christopher_bennage/pages/building-a-wpf-application-table-of-contents.aspx" target="_blank"&gt;Table of Contents&lt;/a&gt;

&lt;p&gt;So let&amp;#39;s get back to this whole building a WPF application thing. &lt;/p&gt; &lt;p&gt;A number of things went down since my last post: I was out sick with a stomach bug for few days, my infant son caught the same bug and subsequently we spent a few days in the hospital (he&amp;#39;s fine now, it was nothing serious), &lt;em&gt;and&lt;/em&gt; I finally caught up on the AAA syntax in &lt;a href="http://www.ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino.Mocks&lt;/a&gt;.&lt;/p&gt; &lt;h3&gt;Changing My Testing Style&lt;/h3&gt; &lt;p&gt;Lots of people have blogged about the AAA syntax &lt;a href="http://www.ayende.com/Blog/archive/2008/05/16/Rhino-Mocks--Arrange-Act-Assert-Syntax.aspx" target="_blank"&gt;here&lt;/a&gt;, &lt;a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/07/24/arrange-act-assert-and-bdd-specifications.aspx" target="_blank"&gt;here&lt;/a&gt;, and &lt;a href="http://blog.jpboodhoo.com/BDDAAAStyleTestingAndRhinoMocks.aspx" target="_blank"&gt;here&lt;/a&gt; (to list a few). I won&amp;#39;t go in depth, but briefly the idea is that you arrange your unit test thusly:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;strong&gt;Arrange&lt;/strong&gt;: do the minimal setup required to execute the test  &lt;li&gt;&lt;strong&gt;Act&lt;/strong&gt;: execute the actual code under test  &lt;li&gt;&lt;strong&gt;Assert&lt;/strong&gt;: assert that the code did what you expected&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I decided to adopt this style. It seems to yield more readable, more focused, and less brittle tests. I rewrote the test from my last post using AAA.&amp;nbsp; The original test was this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class The_presenter_for_the_home_feed : TestFixtureBase
{
    private HomePresenter _presenter;
    private IFeedRepository _feedRepository;

    protected override void given_the_context_of()
    {
        _feedRepository = Mocks.StrictMock&amp;lt;IFeedRepository&amp;gt;();
        _presenter = new HomePresenter(_feedRepository);
    }

    [Test]
    public void can_refresh_the_home_feed()
    {
        using (Record)
        {
            Expect.Call(_feedRepository.FetchHomeFeed())
                .Return(new List&amp;lt;Entry&amp;gt;());
        }

        using (Playback)
        {
            _presenter.RefreshHomeFeed();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;and I rewrote it as this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class The_presenter_for_the_home_feed : TestFixtureBase
{
    private HomePresenter _presenter;
    private IFeedRepository _feedRepository;

    protected override void given_the_context_of()
    {
        _feedRepository = MockRepository.GenerateStub&amp;lt;IFeedRepository&amp;gt;();
        _presenter = new HomePresenter(_feedRepository);
    }

    [Test]
    public void can_refresh_the_home_feed_when_credentials_are_available()
    {
        _presenter.RefreshHomeFeed();
        _feedRepository.AssertWasCalled(x =&amp;gt; x.FetchHomeFeed());
    }
}&lt;/pre&gt;
&lt;p&gt;Again, you can gather more details about this approach in one of the links above. &lt;/p&gt;
&lt;p&gt;One interesting note though is that &lt;strong&gt;AssertWasCalled&lt;/strong&gt; is an extension method and we&amp;#39;re using it to assert the method FetchHomeFeed() was actually called on feedRepository. &lt;/p&gt;
&lt;p&gt;(I also think that I should &lt;em&gt;not&lt;/em&gt; have used StrickMock in the original test, as that added to fragility of the test.)&lt;/p&gt;
&lt;p&gt;I tend to think of my code in terms of sentences and paragraphs, at least when it comes to the use of white space. You&amp;#39;ll notice as the tests get a little larger that there will usually be three &amp;quot;paragraphs&amp;quot; in the code: arrange, act, assert.&lt;/p&gt;
&lt;h3&gt;Focusing on the Story&lt;/h3&gt;
&lt;p&gt;I said in my last post that the core story for this application is &lt;em&gt;to retrieve the home feed.&lt;/em&gt; As such, I&amp;#39;d like to take the shortest path to getting that feature fully functional.&amp;nbsp; The next few steps are roughly:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Write a proxy to wrap the existing FriendFeed api, but just enough to fetch the home feed. 
&lt;li&gt;Write a repository that will manage the home feed data. Even though this seems superfluous at the moment, it&amp;#39;s a seam in the application where I will add future functionality (such as caching, logging, etc.). 
&lt;li&gt;Provide support for authentication.&amp;nbsp; The FriendFeed api requires a username and remote key for accessing the home feed.&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Very soon, I want to be able to launch the application, click a Refresh button, and see my feed. If I haven&amp;#39;t provided credentials, I want the application to prompt me for them.&lt;/p&gt;
&lt;h3&gt;The Credentials Problem&lt;/h3&gt;
&lt;p&gt;The parts of the story regarding credentials raise some interesting design questions. Let&amp;#39;s consider some of the pieces of the puzzle.&lt;/p&gt;
&lt;p&gt;The HomePresenter is going to initiate the act getting the home feed. We&amp;#39;ve already seen that HomePresenter is going to invoke some implementation of IFeedRepository. The repository will talk to the FriendFeed api through a wrapper (IFriendFeedProxy) . Inside the wrapper class is the official .NET FriendFeed client, and it is the class that is really interested in the credentials. It&amp;#39;s what talks to the FriendFeed web service, and that needs to be authenticated with the credentials. So at the bottom of this, somewhere in our code, we&amp;#39;ll have this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;FriendFeedClient client = new FriendFeedClient(&amp;quot;username&amp;quot;, &amp;quot;remoteKey&amp;quot;);&lt;/pre&gt;
&lt;p&gt;&lt;img style="border-right:0px;border-top:0px;border-left:0px;border-bottom:0px;" height="279" alt="classes" src="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildingaWPFApplicationPart2_F0F6/classes_3.png" width="336" align="right" border="0" /&gt;I&amp;#39;m using the &lt;a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle" target="_blank"&gt;Dependency Inversion Principle&lt;/a&gt; (which I&amp;#39;ll talk about more later). However a consequence of this is that the constructor for HomePresenter takes an IFeedRepository and an IApplicationController. &lt;/p&gt;
&lt;p&gt;In turn, my implementation of IFeedRepository, cleverly named &lt;em&gt;FeedRepository&lt;/em&gt;, requires an instance of IFriendProxy in its constructor. My implementation of IFriendProxy wraps the official api. Did you follow all of that?&lt;/p&gt;
&lt;p&gt;When I first began working through the design, I thought that I&amp;#39;d have to request the credentials from the user at the presenter level, and then pass them down to the repository, then to the proxy which would in turn set them on the actual client. &lt;em&gt;But I could tell quickly that this smelled bad.&lt;/em&gt; The repository doesn&amp;#39;t need to be concerned with credentials, and neither the HomePresenter. So far there are really just two classes that need to know about credentials: some sort of UI for getting the credentials from the user (that is a presenter of some sort) and FriendFeedProxy. &lt;/p&gt;
&lt;p&gt;Oh and what&amp;#39;s this IApplicationController interface all about? Um, I&amp;#39;ll come back to that in the next post. &lt;/p&gt;
&lt;h3&gt;Single Source&lt;/h3&gt;
&lt;p&gt;Ideally, what I want is a single source for the credentials: a class whose sole responsibility is managing the current set of credentials. This lead me to create an ICredentialsSource interface. In order to flesh out what the interface should look like I began writing tests for how the client proxy would interact with it:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class The_client_for_FriendFeed
{
    private const string _username = &amp;quot;your_username&amp;quot;;
    private const string _remotekey = &amp;quot;your_remotekey&amp;quot;;
    private ICredentialsSource _credentials;
    private FriendFeedProxy _client;

    [SetUp]
    public void given_the_context_of()
    {
        _credentials = MockRepository.GenerateStub&amp;lt;ICredentialsSource&amp;gt;();
        _client = new FriendFeedProxy(_credentials);
    }

    [Test]
    public void can_get_the_home_feed_when_authenticated()
    {
        _credentials.Stub(x =&amp;gt; x.UserName).Return(_username);
        _credentials.Stub(x =&amp;gt; x.RemoteKey).Return(_remotekey);
        _credentials.Raise(x =&amp;gt; x.CredentialsChanged += null, _credentials, EventArgs.Empty);

        var feed = _client.FetchHomeFeed();

        IList&amp;lt;Entry&amp;gt; entries = feed.ToList();
        Assert.That(entries[0].Id, Is.Not.Null);
        Assert.That(entries[0].Title, Is.Not.Null);
        Assert.That(entries[0].Published, Is.Not.Null);
    }

    [Test]
    [ExpectedException(typeof (WebException))]
    public void cannot_get_the_home_feed_when_not_authenticated()
    {
        var feed = _client.FetchHomeFeed();
    }

    [Test]
    public void updates_credentials_when_the_credentials_source_changes()
    {
        //arrange
        _credentials.Stub(x =&amp;gt; x.UserName).Return(_username);
        _credentials.Stub(x =&amp;gt; x.RemoteKey).Return(_remotekey);

        //act
        Assert.That(_client.DoesClientHaveCredentials, Is.False);
        _credentials.Raise(x =&amp;gt; x.CredentialsChanged += null, _credentials, EventArgs.Empty);

        //assert
        Assert.That(_client.DoesClientHaveCredentials, Is.True);
    }
}&lt;/pre&gt;
&lt;p&gt;These tests live in my &lt;strong&gt;IntegrationTests&lt;/strong&gt; assembly, separate from my &amp;quot;real&amp;quot; unit test is the &lt;strong&gt;Specifications&lt;/strong&gt; assembly. I consider these tests to be &lt;em&gt;integration tests&lt;/em&gt; because they actually interact with the web services. They are not run as often as my Specifications.&lt;/p&gt;
&lt;p&gt;I found these tests hard to write, and I would appreciate any feedback on how to improve them.&lt;/p&gt;
&lt;p&gt;My point here though is to illustrate how these tests led me to create ICredentialsSource. I know that there will be a little more to it, a method perhaps that will allow me to set the credentials, but we&amp;#39;ll get to that when we need it.&lt;/p&gt;
&lt;p&gt;Right now, the interface looks like this:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public interface ICredentialsSource
{
    string UserName { get; }
    string RemoteKey { get; }
    event EventHandler CredentialsChanged;
}&lt;/pre&gt;
&lt;p&gt;I obviously need the username and remote key (and I was tempted to create a class that represented them as a unit.) I also discovered that I wanted the credentials source to raise a change notification event so that the proxy client would be aware when the user changed them.&lt;/p&gt;
&lt;p&gt;Some other places in the application will actually set the credentials on this source, perhaps a yet-unwritten presenter whose job will be to request them from the user. This really helps to decouple responsibilities and keep the code clean. For this approach to work however, our application will need a single instance of this class. I&amp;#39;ll show how I&amp;#39;ll handle that when we cover dependency injection.&lt;/p&gt;
&lt;h3&gt;Next&lt;/h3&gt;
&lt;p&gt;I had a lot of interruptions trying to complete this post, and I had to go back reread what I&amp;#39;ve written so far. In doing so, I realized that I ought to take a step back and explain my overall default architecture that I&amp;#39;m using. That will be the subject of my next post; and &lt;em&gt;I promise&lt;/em&gt; to get the actual WPF bits soon!&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2008/08/20/building-a-wpf-application-part-3.aspx"&gt;On to Part 3.&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=41865" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Software+Architecture/default.aspx">Software Architecture</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ChumChase/default.aspx">ChumChase</category></item><item><title>Building a WPF Application: Part 1</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/07/22/building-a-wpf-application-part-1.aspx</link><pubDate>Tue, 22 Jul 2008 23:51:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:41392</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>6</slash:comments><description>&lt;a title="Table of Contents for ChumChase" href="http://devlicious.com/blogs/christopher_bennage/pages/building-a-wpf-application-table-of-contents.aspx" target="_blank"&gt;Table of Contents&lt;/a&gt;

&lt;p&gt;I actually meant to say in my &lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2008/07/20/build-a-wpf-application-part-0.aspx" target="_blank"&gt;last post&lt;/a&gt; that I had investigated the API options for FriendFeed and they have a C# wrapper already available &lt;a href="http://code.google.com/p/friendfeed-api/downloads/list" target="_blank"&gt;here&lt;/a&gt;. It&amp;#39;s packaged up in a single download with its Python and PHP counterparts.&amp;nbsp; Unfortunately, it has compilation errors. I fixed the errors and then I let &lt;a href="http://www.jetbrains.com/resharper/documentation/" target="_blank"&gt;ReSharper (R#)&lt;/a&gt; have its way with it [&lt;em&gt;R#: Ctrl+Alt+Shift+F].&lt;/em&gt; Yes, I do understand that the Code Cleanup feature of R# can be a nuclear bomb of churn for diffing your source, but &lt;em&gt;&lt;a title="yes, it&amp;#39;s valid!" href="http://www.morewords.com/word/egads/" target="_blank"&gt;egads&lt;/a&gt;&lt;/em&gt; I do love it so.&lt;/p&gt; &lt;p&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildingaWPFApplicationPart1_3D0/soln01_2.png"&gt;&lt;img style="border-right:0px;border-top:0px;margin:0px 0px 0px 4px;border-left:0px;border-bottom:0px;" height="411" alt="FriendFeed project in the solution explorer" src="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildingaWPFApplicationPart1_3D0/soln01_thumb.png" width="258" align="right" border="0" /&gt;&lt;/a&gt;I also broke out the FriendFeed classes into separate files [&lt;em&gt;R#: F6]&lt;/em&gt;.&lt;/p&gt; &lt;p&gt;&lt;em&gt;Hmm, I &lt;a href="http://devlicio.us/blogs/christopher_bennage/pages/resharper-shortcuts.aspx" target="_blank"&gt;just decided&lt;/a&gt; that I&amp;#39;ll notate R# and VisualStudio keyboard shortcuts like this [app:shortcut]. Is there already a convention for that out there?&lt;/em&gt;&lt;/p&gt; &lt;p&gt;I also decided to keep the FriendFeed code in a separate assembly. I don&amp;#39;t always advocate &lt;a href="http://www.lostechies.com/blogs/chad_myers/archive/2008/07/15/project-anti-pattern-many-projects-in-a-visual-studio-solution-file.aspx" target="_blank"&gt;assembly proliferation&lt;/a&gt;, but it made sense in this case. I created a project called FriendFeed and moved all their classes there.&amp;nbsp; I also preserved their namespace, FriendFeed, as well. (I&amp;#39;m getting tired of typing &amp;quot;FriendFeed&amp;quot;.)&lt;/p&gt; &lt;p&gt;At this point, I just wanted to get a feel for the API. So I read over what appeared to be the significant classes, and I used a couple of tests to see how it really works. Simple enough, instantiate the client and call FetchHomeFeed().&lt;/p&gt; &lt;h3&gt;Building in Seams&lt;/h3&gt; &lt;p&gt;I picked up the term &lt;em&gt;seam&lt;/em&gt; from Ayende in this &lt;a href="http://www.ayende.com/Blog/archive/2007/03/03/The-Production-Value-of-Seams.aspx" target="_blank"&gt;post&lt;/a&gt;. You can think of a seam as a natural boundary in an application. It&amp;#39;s a place where you easily extend or modify an application. It&amp;#39;s a little bit like a &lt;a href="http://domaindrivendesign.org/discussion/messageboardarchive/BoundedContext.html" target="_blank"&gt;Bounded Context&lt;/a&gt;, but just a little. I used to try to coerce my design into the metaphor of &lt;em&gt;layers&lt;/em&gt;, but seams are a more natural concept. You might also think of them as a way of describing componentized architecture.&lt;/p&gt; &lt;p&gt;Consider the example of a desktop computer: you have a motherboard, CPU, memory, video card, etc. All of the components are required for the computer to function, but you can replace any one of them. You can extend the functionality of the computer by adding more hardware. Some things might be tightly coupled, like those wretched integrated video cards. But you don&amp;#39;t think of these components as layers. This is a flexible way to architect your application.&lt;/p&gt; &lt;p&gt;Seams are a standard consideration for me when it comes to designing an application. Yes, you can go crazy with it, you can go crazy with anything. In the case of ChumChase, I don&amp;#39;t want to be tightly coupled to the official API. I have a few reasons right now: [a] the official API might change. [b] I might want to implement my own API against their web services just for kicks [c] it&amp;#39;s a good excuse to demonstrate the technique. I&amp;#39;m going to hide the FriendFeed API behind a repository. The IFeedRepository interface will be a seam in my application.&lt;/p&gt; &lt;h3&gt;MVP&lt;/h3&gt; &lt;p&gt;I mentioned before that I&amp;#39;m going to use Model-View-Presenter. This pattern is similar to MVC, and like barbeque sauce, everyone has their own flavor. In my case, a presenter is a class that represents the &lt;em&gt;behavior&lt;/em&gt; of the UI, and possibly some state. It is ignorant of how the UI visually appears. The view will be a user control, window, page, tab item, etc. We&amp;#39;ll use data binding to glue the two together. The ignorance of the presenter about the view is important because it helps us to isolate the presenter in our unit tests.&lt;/p&gt; &lt;h3&gt;TDD&lt;/h3&gt; &lt;p&gt;It&amp;#39;s &lt;strike&gt;sometimes&lt;/strike&gt; hard to decide where to start writing to tests. I tend to write tests that reflect the &lt;em&gt;behaviors of the user interacting with the application&lt;/em&gt;. This is as opposed to testing how the application might interact with a data source, or some other more internal function of the application. This approach of working from the outside in helps prevent me from making too many assumptions about the internals.&amp;nbsp; The negative is that I have to provide mocks or stubs for the dependencies that I haven&amp;#39;t written yet.&lt;/p&gt; &lt;p&gt;My core story, that is the basic behavior that I&amp;#39;m interested in, is for the application to fetch my home feed. I&amp;#39;ll place this feature on a class called HomePresenter. HomePresenter might end up being my only presenter, I don&amp;#39;t know yet. It common though for applications to have several presenters. We&amp;#39;ll talk later about how to logically organize presenters.&lt;/p&gt; &lt;p&gt;Let&amp;#39;s look at a test:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class The_presenter_for_the_home_feed : TestFixtureBase
{
    private HomePresenter _presenter;
    private IFeedRepository _feedRepository;

    protected override void given_the_context_of()
    {
        _feedRepository = Mocks.StrictMock&amp;lt;IFeedRepository&amp;gt;();
        _presenter = new HomePresenter(_feedRepository);
    }

    [Test]
    public void can_refresh_the_home_feed()
    {
        using (Record)
        {
            Expect.Call(_feedRepository.FetchHomeFeed())
                .Return(new List&amp;lt;Entry&amp;gt;());
        }

        using (Playback)
        {
            _presenter.RefreshHomeFeed();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;First, my TestFixtureBase is just an abstract class to reduce clutter. The Mocks, Record, and Playback properties all exist on it and they are really just pass-throughs to Rhino.Mocks. Likewise, I have a setup method in TestFixtureBase that calls &lt;em&gt;given_the_context_of()&lt;/em&gt; before each test is executed. It&amp;#39;s meant to reset the system-under-test (SUT) into a consistent and pristine state.&lt;/p&gt;
&lt;p&gt;Notice that I named my class and method such that they read as a specification for the behavior I&amp;#39;m testing: &lt;em&gt;The presenter for the home feed can refresh the home feed.&lt;/em&gt; I&amp;#39;m not sure that I like saying &amp;quot;presenter&amp;quot; in the specification. If I was working with non-technical users, that wouldn&amp;#39;t make sense to them. I could replace it with &amp;quot;UI&amp;quot; or &amp;quot;interface&amp;quot; or &amp;quot;screen&amp;quot; perhaps.&lt;/p&gt;
&lt;p&gt;The test has two blocks or phases: record and playback. This is generally a big stumbling block for people. I know when I first encountered it I was thoroughly confused. The record phase is where I tell the test what I&amp;#39;m expecting to happen during the playback phase.&amp;nbsp; The record phase plays the same roles as asserts.&lt;/p&gt;
&lt;p&gt;The function we are really testing here is:&lt;/p&gt;
&lt;p&gt;_presenter.RefreshHomeFeed(); &lt;/p&gt;
&lt;p&gt;Since there is not a state that I can verify after calling RefreshHomeFeed(), I am checking to make sure that it&amp;#39;s doing what I expect it to do. That is, I expect it to get a list of entries from a repository of feeds.&lt;/p&gt;
&lt;p&gt;The Expect.Call().Return() is Rhino.Mocks syntax that allows me to say: &lt;em&gt;I expect my SUT to execute _feedRepository.FetchHomeFeed() and I expect that to return a List&amp;lt;Entry&amp;gt; instance.&lt;/em&gt; Right now Entry is just an empty class, but conceptually it represents a single item in the feed. You should also note that the relationship between my presenter and the repository is established in given_the_context_of().&lt;/p&gt;
&lt;p&gt;Yes, this is a simple test, but writing this test helped me to shake out what I needed.&amp;nbsp; Unfortunately, the test as it stands here does not reflect the process of writing it.&amp;nbsp; I wrote some things, decided they didn&amp;#39;t look right, changed them a bit and so on. It probably took me 10 minutes or so before I settled on what you see.&lt;/p&gt;
&lt;p&gt;Moving on to the next test. This is in the same class, so you can read it as: &lt;em&gt;The presenter for the home feed notifies the UI when the home feed is refreshed.&lt;/em&gt;&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Test]
public void notifies_the_UI_when_the_home_feed_is_refreshed()
{
    var property_has_changed = false;

    _presenter.PropertyChanged +=
        (s, e) =&amp;gt; { property_has_changed = (e.PropertyName == &amp;quot;HomeFeed&amp;quot;); };

    _presenter.RefreshHomeFeed();

    Assert.That(property_has_changed);
}&lt;/pre&gt;
&lt;p&gt;I want to verify that when I call _presenter.RefreshHomeFeed() a change notification is raised for the HomeFeed property. This means my presenter needs a HomeFeed property. I have a boolean flag that helps me track the state and I&amp;#39;m using an inline delegate to set my flag when the property is changed. (There&amp;#39;s actually a flaw in this test that we&amp;#39;ll examine later, can you see it?)&amp;nbsp; &lt;/p&gt;
&lt;p&gt;I don&amp;#39;t like strings though. If I happen to change the name of the HomeFeed property and forget to change the string in the test, I&amp;#39;ve broken my test. Of course, I&amp;#39;ll notice as soon as I run the tests, but it would sure be nice to eliminate the string. So I wrote this extension method for PropertyChangedEventArgs:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;public static bool HasChanged&amp;lt;T&amp;gt;(this PropertyChangedEventArgs args, Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; property)
{
    var expression = (MemberExpression)property.Body;
    return expression.Member.Name == args.PropertyName;
}&lt;/pre&gt;
&lt;p&gt;Now I can change my test to the following and eliminate the string:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;[Test]
public void notifies_the_UI_when_the_home_feed_is_refreshed()
{
    var property_has_changed = false;

    _presenter.PropertyChanged +=
        (s, e) =&amp;gt; { property_has_changed = e.HasChanged(() =&amp;gt; _presenter.HomeFeed); };

    _presenter.RefreshHomeFeed();

    Assert.That(property_has_changed);
}&lt;/pre&gt;
&lt;p&gt;Of course, in between these tests I was writing code to make them pass. (&lt;a href="http://geekswithblogs.net/WillSmith/archive/2008/03/18/red-green-refactor.aspx" target="_blank"&gt;Red -&amp;gt; Green -&amp;gt; Refactor&lt;/a&gt;, right?) Here&amp;#39;s what my presenter class looked liked afterwards:&lt;/p&gt;&lt;pre class="c#:nogutter:nocontrols" name="code"&gt;using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using ChumChase.Extensions;

namespace ChumChase.Presenters
{
    public class HomePresenter : INotifyPropertyChanged
    {
        private readonly IFeedRepository _feedRepository;
        private IList&amp;lt;Entry&amp;gt; _homeFeed;

        public HomePresenter(IFeedRepository feedRepository)
        {
            _feedRepository = feedRepository;
        }

        public IList&amp;lt;Entry&amp;gt; HomeFeed
        {
            get { return _homeFeed; }
            private set
            {
                _homeFeed = value;
                OnPropertyChanged( ()=&amp;gt; HomeFeed);
            }
        }

        public void RefreshHomeFeed()
        {
            HomeFeed = _feedRepository.FetchHomeFeed();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged&amp;lt;T&amp;gt;(Expression&amp;lt;Func&amp;lt;T&amp;gt;&amp;gt; property)
        {
            if (PropertyChanged != null) PropertyChanged(this, property.CreateChangeEventArgs());
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The source is now available &lt;a href="http://www.codeplex.com/chumchase" target="_blank"&gt;here&lt;/a&gt;. &lt;strike&gt;More to come!&lt;/strike&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2008/08/16/building-a-wpf-application-part-2.aspx" target="_blank"&gt;Continue to Part 2&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=41392" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Software+Architecture/default.aspx">Software Architecture</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ChumChase/default.aspx">ChumChase</category></item><item><title>Building a WPF Application: Part 0</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/07/20/build-a-wpf-application-part-0.aspx</link><pubDate>Mon, 21 Jul 2008 03:18:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:41363</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>10</slash:comments><description>&lt;a title="Table of Contents for ChumChase" href="http://devlicious.com/blogs/christopher_bennage/pages/building-a-wpf-application-table-of-contents.aspx" target="_blank"&gt;Table of Contents&lt;/a&gt;

&lt;p&gt;In a rather indirect way, I was inspired by a commenter on &lt;a title="BabySmash + Books = Good WPF" href="http://www.hanselman.com/blog/LearningWPFWithBabySmashAndBackToBasicsMakingAssumptionsAndWhenToTurnToBooks.aspx" target="_blank"&gt;one of Scott Hanselman&amp;#39;s posts&lt;/a&gt; to begin a series that walks through building a WPF application from start to finish. We did this for four different applications in &lt;a title="I just can&amp;#39;t get enough of linking to our book!" href="http://www.amazon.com/gp/product/0672329859?&amp;amp;camp=212361&amp;amp;linkCode=wey&amp;amp;tag=bluspiconinc-20&amp;amp;creative=380733" target="_blank"&gt;our book&lt;/a&gt;, but those where targeted to demonstrate particular facets of WPF whereas in these (yet unwritten) posts I&amp;#39;d like to focus more on &amp;quot;this is how I build my WPF apps&amp;quot;. Not to say that my way is the *right way*, but so that we might learn together. In the spirit of the aforementioned post, I&amp;#39;m bound to make mistakes, so please (gently) correct me when you think you see one.&lt;/p&gt; &lt;h3&gt;What to build?&lt;/h3&gt; &lt;p&gt;You might not have noticed, but there&amp;#39;s quite a bit of .NET chatter in &lt;a href="http://twitter.com/" target="_blank"&gt;twit-space&lt;/a&gt;. There are already lots of Twitter clients, and &lt;a title="Witty" href="http://code.google.com/p/wittytwitter/" target="_blank"&gt;some are WPF&lt;/a&gt;, so that path has been rigorously trod. However, the &lt;a href="http://www.techcrunch.com/2008/05/20/twitter-something-is-technically-wrong/" target="_blank"&gt;technical difficulties&lt;/a&gt; surrounding Twitter has given rise to the popularity of another mash up web 2.0 thingy app called &lt;a href="http://friendfeed.com/" target="_blank"&gt;FriendFeed&lt;/a&gt;.&amp;nbsp; Everyone seems to agree that the web interface for FriendFeed is all stinky bad, &lt;em&gt;and&lt;/em&gt; there&amp;#39;s an &lt;a href="http://code.google.com/p/friendfeed-api/wiki/ApiDocumentation" target="_blank"&gt;API&lt;/a&gt; readily available, so I think a FriendFeed client is in order.&lt;/p&gt; &lt;p&gt;&lt;img style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="53" alt="ff_logo" src="http://devlicious.com/blogs/christopher_bennage/WindowsLiveWriter/BuildaWPFApplicationPart0_FA/ff_logo_3.png" width="234" align="right" border="0" /&gt; Briefly, FriendFeed is a way to consolidate all of your creepy Internet voyeurism in one spot. You can track a friend&amp;#39;s Flickr account, NetFlix queue, Amazon wishlist, and yes, their Twitter tweets and much, much more. Oh yeah, and you can subscribe to me &lt;a title="please, pay attention to me! I&amp;#39;m really cool! Really!" href="http://friendfeed.com/bennage" target="_blank"&gt;here&lt;/a&gt;. (I&amp;#39;m such a loser.)&lt;/p&gt; &lt;h3&gt;What to do?&lt;/h3&gt; &lt;p&gt;I&amp;#39;m not going to set an agenda or outline a detailed plan. I&amp;#39;m just going to post as I have time to work on it. I started tonight, so I&amp;#39;m expecting to have a real Part 1 posted by midweek. I&amp;#39;ve already set up a project at &lt;a href="http://www.codeplex.com/" target="_blank"&gt;CodePlex&lt;/a&gt; (though it won&amp;#39;t be published for a few more days still.) I named it &lt;a href="http://www.codeplex.com/chumchase" target="_blank"&gt;ChumChase&lt;/a&gt;. Isn&amp;#39;t that great? &lt;/p&gt; &lt;p&gt;Part of my plan is to step you through my thinking and decision making process in sort of &lt;a title="I&amp;#39;m talking about Jimmy Nilsson." href="http://www.amazon.com/Applying-Domain-Driven-Design-Patterns-Examples/dp/0321268202/ref=sr_1_1?ie=UTF8&amp;amp;s=books&amp;amp;qid=1216528167&amp;amp;sr=8-1" target="_blank"&gt;Nilssonian&lt;/a&gt; way. I&amp;#39;ve only just begun but here&amp;#39;s what I can tell you so far.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;I&amp;#39;m going to use a Model-View-Presenter pattern  &lt;li&gt;Expect to see some DDD artifacts. &lt;li&gt;I&amp;#39;m going to use &lt;a title="wow, can you believe that I actually linked to NUnit?" href="http://www.nunit.org/index.php" target="_blank"&gt;NUnit&lt;/a&gt; and &lt;a href="http://www.ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;RhinoMocks&lt;/a&gt;.  &lt;li&gt;I&amp;#39;ll probably use &lt;a href="http://castleproject.org/container/index.html" target="_blank"&gt;Windsor&lt;/a&gt; too (or maybe &lt;a href="http://structuremap.sourceforge.net/Default.htm" target="_blank"&gt;StructureMap&lt;/a&gt; though, anybody have a preference?) &lt;/li&gt;&lt;/ul&gt; &lt;p&gt;I had intended to write a set of user stories&amp;nbsp; using the issue tracker of CodePlex. However, I got tired of retyping them every time the site errorred out, which was about 60% of the time. (Is that typical for the CodePlex issue tracker? This was my first usage.)&amp;nbsp; It also occurred to me that I am lazy and ought to have a life outside of coding, so sorry no user stories.&lt;/p&gt; &lt;h3&gt;What to think?&lt;/h3&gt; &lt;p&gt;I&amp;#39;m all about conversation. If this interests you, please let me know. I welcome (friendly) criticisms as well. The more I hear, the more motivated I&amp;#39;ll be to do it. (Believe me there&amp;#39;s a lot to distract right now. I had a new baby son born on the 10th.)&lt;/p&gt;
&lt;p&gt;&lt;a href="http://devlicious.com/blogs/christopher_bennage/archive/2008/07/22/building-a-wpf-application-part-1.aspx"&gt;Continue to Part 1&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=41363" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/WPF/default.aspx">WPF</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Software+Architecture/default.aspx">Software Architecture</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/.NET/default.aspx">.NET</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/ChumChase/default.aspx">ChumChase</category></item><item><title>Phil Haack: Research on TDD</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2008/01/22/phil-haack-research-on-tdd.aspx</link><pubDate>Tue, 22 Jan 2008 16:52:22 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:39288</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;Phil Haack has an &lt;a href="http://haacked.com/archive/2008/01/22/research-supports-the-effectiveness-of-tdd.aspx" target="_blank"&gt;interesting post&lt;/a&gt; on some research regarding the effectiveness of &lt;em&gt;Test Driven Development.&lt;/em&gt; I&amp;#39;m really glad to know that this sort of work is going on, and the results are, er, moderately encouraging to the TDD enthusiast. This topic of research supporting methodologies has been a bit contentious of late. These subjects seem like they would be very difficult to analyze because there are some many factors involved (from skill level of the individual developers to the qualification of &amp;#39;what good code is&amp;#39;.) Nevertheless, carry on my good researchers!&lt;/p&gt; &lt;p&gt;Now, I want to hook up with a CS department. Anyone out there from the &lt;a href="http://www.cs.fsu.edu/" target="_blank"&gt;FSU CS&lt;/a&gt; department reading this? :-)&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=39288" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category></item><item><title>TDD Example: Querying a Repository</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2007/08/26/tdd-example-querying-a-repository.aspx</link><pubDate>Mon, 27 Aug 2007 03:07:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38280</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>7</slash:comments><description>&lt;p&gt;I&amp;#39;m always a little intimidated when I post code examples.&amp;nbsp; There are a lot of smart (and opinionated) people out there reading blogs.&amp;nbsp; Fear won&amp;#39;t get us anywhere though.&amp;nbsp; That said, I&amp;#39;m posting this example and asking for criticism.&lt;/p&gt; &lt;p&gt;Here&amp;#39;s the story.&amp;nbsp; A school of music needs to schedule auditions for incoming students. The faculty need to be able to view the schedule for the next two upcoming terms, and some of staff needs to be able to edit the audition schedule.&lt;/p&gt; &lt;p&gt;The &amp;quot;schedule&amp;quot; is really a set of rooms set aside on certain dates for certain types of students.&amp;nbsp; For example, room&amp;nbsp;1874 will be used for violins on September 21. Thus, a ScheduledRoom is a certain on a certain date, with rules about who can audition&amp;nbsp;there. &amp;nbsp;Right now, we&amp;#39;re just concerned with retrieving the list of rooms for a given Term, which is a unique combination of year and semester. &lt;/p&gt; &lt;p&gt;We have a repository for handling audition schedules, and a service that talks to the repository.&amp;nbsp; The service is in turn accessed by a desktop client, and a web client.&amp;nbsp; I&amp;#39;m going to focus on just the repository here.&lt;/p&gt;&lt;pre class="c-sharp:nogutter:nocontrols" name="code"&gt;namespace Specifications.Integrated.The_repository_for
{
    [TestFixture]
    public class the_audition_schedule
    {
        private AuditionScheduleRepository _repository;

        [SetUp]
        public void SetUp
        {
            _repository = new AuditionScheduleRepository();
        }

        [Test, RollBack]
        public void can_retrieve_the_list_of_scheduled_rooms_for_a_given_term()
        {
            //setup data for test
            Term fall2000 = a_term_for_Fall_2000();
            Term spring2001 = a_term_for_Spring_2001();

            schedule_a_room_for_(fall2000);
            schedule_a_room_for_(fall2000);
            schedule_a_room_for_(fall2000);
            schedule_a_room_for_(spring2001);

            //here&amp;#39;s the actual code under test
            IList&amp;lt;ScheduledRoom&amp;gt; rooms = _repository.GetRooms(fall2000);

            //verify the results
            Assert.AreEqual(3, rooms.Count);
        }
    }
}
&lt;/pre&gt;
&lt;p&gt;The methods &lt;b&gt;a_term_for_Fall_2000()&lt;/b&gt;, &lt;b&gt;a_term_for_Spring_2001()&lt;/b&gt;, and &lt;b&gt;schedule_a_room_for_()&lt;/b&gt; are helper methods that do nothing more than&amp;nbsp;persist some test data.&amp;nbsp; In my [Setup], I create a new instance of _repository, so that it&amp;#39;s fresh for every test.&lt;/p&gt;
&lt;p&gt;What am I really testing here?&amp;nbsp; An important question, &lt;a title="Los Techies" href="http://www.lostechies.com/blogs/joeydotnet/default.aspx" target="_blank"&gt;Joey Beninghove&lt;/a&gt; has a good post on the topic &lt;a title="Unit Testing NHibernate DALs - What Are You *Really* Testing?" href="http://www.lostechies.com/blogs/joeydotnet/archive/2007/05/17/unit-testing-nhibernate-dals-what-are-you-really-testing.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;I want to ensure that GetRooms() &lt;i&gt;behaves&lt;/i&gt; the way I expect.&amp;nbsp; I expect it to return 3 out of the 4 terms I have persisted. The actual implementation for GetRooms() builds an NHibernate.ICriteria and call its List&amp;lt;&amp;gt;() method.&lt;/p&gt;
&lt;p&gt;Thoughts? Comments?&amp;nbsp; More examples to come...&lt;/p&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://devlicious.com/blogs/christopher_bennage/archive/2007/08/26/tdd-example-querying-a-repository.aspx"&gt;&lt;img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://devlicious.com/blogs/christopher_bennage/archive/2007/08/26/tdd-example-querying-a-repository.aspx" border="0" /&gt;&lt;/a&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38280" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Featured/default.aspx">Featured</category></item><item><title>Confidence in your code</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2007/08/22/confidence-in-your-code.aspx</link><pubDate>Thu, 23 Aug 2007 02:53:42 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:38259</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>3</slash:comments><description>&lt;p&gt;First, I highly recommend&amp;nbsp;Kent Beck&amp;#39;s &lt;a title="you should read this book" href="http://www.amazon.com/Test-Driven-Development-Addison-Wesley-Signature/dp/0321146530/" target="_blank"&gt;Test Driven Development: By Example&lt;/a&gt;.&amp;nbsp; It&amp;#39;s an excellent book.&lt;/p&gt; &lt;p&gt;I mentioned Beck&amp;#39;s book, because it is there that I gained an insight affecting the way I&amp;#39;m writing unit tests.&amp;nbsp; (&lt;em&gt;So Christopher, you&amp;#39;re saying that one of the seminal works on unit testing has affected the way you are writing tests?&amp;nbsp; Um, yes, I am saying that.&lt;/em&gt;)&lt;/p&gt; &lt;p&gt;Kent asks a question about when you should remove duplicate or overlapping tests.&amp;nbsp; His answer was that if it doesn&amp;#39;t decrease your confidence in the code, then it&amp;#39;s okay to delete it.&amp;nbsp; (I hope I&amp;#39;m getting that right, my copy is loaned out&amp;nbsp;at the moment.)&lt;/p&gt; &lt;p&gt;My current project uses WCF to handle communication from the desktop client to the server.&amp;nbsp; We have a set of interfaces for our services shared in a common assembly.&amp;nbsp; When I create a new interface, I always forget to decorate it with the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.aspx" target="_blank"&gt;ServiceContract&lt;/a&gt; attribute, or I&amp;#39;ll create&amp;nbsp;a DTO and forget the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.aspx" target="_blank"&gt;DataContract&lt;/a&gt;/&lt;a href="http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx" target="_blank"&gt;DataMember&lt;/a&gt; attributes, or (and here&amp;#39;s the worst) I&amp;#39;ll forget to add the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.security.permissions.principalpermissionattribute.aspx" target="_blank"&gt;PrincipalPermission&lt;/a&gt; attribute to the actual implementation of our services!&lt;/p&gt; &lt;p&gt;This has been bothering me for a month or two, and finally it dawned on me: why don&amp;#39;t I write tests for all of this?&amp;nbsp; I&amp;#39;m not confident in the code, I&amp;#39;m fearful that I&amp;#39;m forgetting things; let&amp;#39;s write tests and remove the doubt!&lt;/p&gt; &lt;p&gt;Here&amp;#39;s what one of the tests looks like:&lt;/p&gt;&lt;pre class="c-sharp:nogutter:nocontrols" name="code"&gt;[TestFixture]
public class Service_interfaces
{
	private const string ASSEMBLY = &amp;quot;SomeAssembly&amp;quot;;
	private const string SERVICE_NAMESPACE = &amp;quot;ServiceInterfaces&amp;quot;;

	[Test]
	public void must_have_a_ServiceContract_attribute()
	{
		bool atLeastOne = false;

		foreach (Type type in Assembly.Load(ASSEMBLY).GetTypes())
		{
			if (type.Namespace.Contains(SERVICE_NAMESPACE))
			{
				atLeastOne = true;

				object[] attributes = type.GetCustomAttributes(typeof (ServiceContractAttribute), false);
				Assert.IsTrue(attributes.Length &amp;gt; 0,
							  string.Format(&amp;quot;The {0} does is not decorated with the ServiceContractAttribute&amp;quot;, type));
			}
		}

		Assert.IsTrue(atLeastOne,
					  string.Format(&amp;quot;No service interfaces were found in {0} in the namepace {1}.&amp;quot;,
									ASSEMBLY,
									SERVICE_NAMESPACE));
	}
}&lt;/pre&gt;
&lt;p&gt;So I am just the last on the bus?&amp;nbsp; What do you think?&amp;nbsp; Is there a better way to handle this?&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=38259" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Reflection/default.aspx">Reflection</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/TDD/default.aspx">TDD</category></item></channel></rss>