<?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 : C#, TDD</title><link>http://devlicio.us/blogs/christopher_bennage/archive/tags/C_2300_/TDD/default.aspx</link><description>Tags: C#, TDD</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><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>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></channel></rss>