<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-1322079872927855793</id><updated>2011-09-15T09:10:58.206-07:00</updated><category term='lame'/><category term='logging'/><category term='concurrency test'/><category term='introduction'/><category term='user acceptance test'/><category term='funny'/><category term='silverlight'/><category term='separation of concern'/><category term='production'/><category term='automated test'/><category term='singleton'/><category term='lamorz'/><category term='unicorn'/><category term='system test'/><category term='integration test'/><category term='mock'/><category term='humour'/><category term='expression blend'/><category term='april fool'/><category term='manual test'/><category term='heart'/><category term='rainbow'/><category term='stack overflow'/><category term='quality assurance'/><category term='webservice'/><category term='test'/><category term='palindrome'/><category term='code format test'/><category term='hello world'/><category term='interface programming'/><category term='WCF'/><category term='unit test'/><category term='user interface'/><category term='fundamental'/><category term='joke'/><category term='dependency'/><category term='design'/><category term='preproduction'/><category term='webservice client'/><category term='framework'/><category term='chess'/><category term='encapsulation'/><category term='system integration test'/><title type='text'>... not so much blogging as blabbing ...</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://jwgerula.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>16</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-7984814469203711331</id><published>2011-04-25T07:46:00.000-07:00</published><updated>2011-04-25T07:50:59.310-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='silverlight'/><category scheme='http://www.blogger.com/atom/ns#' term='logging'/><category scheme='http://www.blogger.com/atom/ns#' term='design'/><category scheme='http://www.blogger.com/atom/ns#' term='expression blend'/><category scheme='http://www.blogger.com/atom/ns#' term='user interface'/><title type='text'>Oi, oi, oi ...</title><content type='html'>Been awhile. A few months back I started working on some material for some logging-based posts, but got side tracked by work and other stuff too. Still on the radar, but also ramping up on some Silverlight - especially the design aspects!&lt;br /&gt;
&lt;br /&gt;
While searching for Silverlight related tutorials and sites, found this gem &lt;a href="http://www.microsoft.com/design/toolbox/"&gt;.toolbox&lt;/a&gt;. It's a clever site with loads of content that I am slowly working through. As a dev, the Expression Blend tutorials are a good way to get familiar with the product. I am especially interested in using Blend to prototype faster so that I may elicit users feedback sooner. I am also enjoying myself with the design sessions, and recommend these to any developer interested in User Interface design work.﻿﻿&lt;br /&gt;
&lt;div class="separator" style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; clear: both; text-align: center;"&gt;﻿ &lt;/div&gt;&lt;table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: 1em; margin-right: 1em; text-align: center;"&gt;&lt;tbody&gt;
&lt;tr&gt;&lt;td style="text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/-atBhTIIC3OM/TbWJNLFa3QI/AAAAAAAAAAw/_EaG3Pdx2r0/s1600/johnny_g.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"&gt;&lt;img border="0" height="200" i8="true" src="http://2.bp.blogspot.com/-atBhTIIC3OM/TbWJNLFa3QI/AAAAAAAAAAw/_EaG3Pdx2r0/s200/johnny_g.jpg" width="150" /&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td class="tr-caption" style="text-align: center;"&gt;.toolbox user avatar for johnny_g&lt;/td&gt;&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;﻿&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-7984814469203711331?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/7984814469203711331'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/7984814469203711331'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2011/04/oi-oi-oi.html' title='Oi, oi, oi ...'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/-atBhTIIC3OM/TbWJNLFa3QI/AAAAAAAAAAw/_EaG3Pdx2r0/s72-c/johnny_g.jpg' height='72' width='72'/></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-7047545936712289333</id><published>2010-10-13T06:05:00.000-07:00</published><updated>2010-10-13T06:07:04.644-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='palindrome'/><category scheme='http://www.blogger.com/atom/ns#' term='heart'/><category scheme='http://www.blogger.com/atom/ns#' term='stack overflow'/><title type='text'>I &lt;3 palindromes ...</title><content type='html'>w00t! Stack Overflow!&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://2.bp.blogspot.com/_24VPmXFKcCg/TLWuKQsjcdI/AAAAAAAAAAk/bmZEgyxqUGE/s1600/iHEARTpalindromes.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" ex="true" src="http://2.bp.blogspot.com/_24VPmXFKcCg/TLWuKQsjcdI/AAAAAAAAAAk/bmZEgyxqUGE/s1600/iHEARTpalindromes.PNG" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div class="separator" style="clear: both; text-align: left;"&gt;Okay, so maybe not so unique, but pretty cool nonetheless!﻿&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-7047545936712289333?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/7047545936712289333'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/7047545936712289333'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/10/i-palindromes.html' title='I &amp;lt;3 palindromes ...'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_24VPmXFKcCg/TLWuKQsjcdI/AAAAAAAAAAk/bmZEgyxqUGE/s72-c/iHEARTpalindromes.PNG' height='72' width='72'/></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-5784889025498700800</id><published>2010-09-27T13:48:00.000-07:00</published><updated>2010-09-27T13:53:19.705-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='mock'/><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, how do I mock a signature with ref or out?</title><content type='html'>So, recently I had the distinct pleasure of mocking a service with method members that contained ref parameters. I thought this rather odd (I have never been a fan of 'in-place' modifications or returns), but not particularly special. That is, not until I came to unit test consumers of the service.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// immutable third-party service interface
public interface ISubmitMessage
{
    // ugly method
    void Submit (string username, string password, ref byte[] message);
}

// our poor poor consumer that has to interface
// with big bad mean service above
public class SubmitAdapter
{
    void Process (ISubmitMessage service)
    {
         // 1. set username and password from configuration
         string username = string.Empty;
         string password = string.Empty;

         // 2. generate byte-encoding of a string message
         byte[] messageBytes = null;

         // 3. invoke service
         service.Submit (username, password, ref messageBytes);

         // 4. inspect messageBytes return value for
         // success\failure
    }
}
&lt;/pre&gt;&lt;br /&gt;
Depending on our mocking solution, ref and out method parameters may or may not be supported. From personal experience many mocking frameworks do not support ref and out parameters. My current mock solution of preference is &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt;, and with Moq v4.0.10827 (beta) we cannot verify pass-in and pass-out parameters out-of-box.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;[Test]
public void Test_Process ()
{
    Mock&amp;lt;ISubmitMessage&amp;gt; service = 
        new Mock&amp;lt;ISubmitMessage&amp;gt; (MockBehavior.Strict);

    string username = "some.username";
    string password = "some.password";
    byte[] messageIn = null;
    byte[] messageOut = new byte[] { 1 };

    // ideally, we would like something similar to this
    service.
        Setup (
        s =&amp;gt; s.Submit (
        username,
        password,

        // where we inspect on way in, and define a return value
        ref It.IsRef&amp;lt;byte[]&amp;gt; (d =&amp;gt; Equals (d, null)).Returns (messageOut)));

    SubmitAdapter adapter = new SubmitAdapter ();
    adapter.Process (service.Object);

    service.VerifyAll ();
}
&lt;/pre&gt;&lt;br /&gt;
Unfortunately, this feature set does not quite exist yet - though as we shall soon see, we do not necessarily &lt;em&gt;need&lt;/em&gt; direct support.&lt;br /&gt;
&lt;br /&gt;
The key to mocking ref and out method parameters is understanding our requirements as a consumer and our requirements as a producer - and while disjoint, they can be satisfied via transform. By example, our consumer expects a functional implementation of a specific interface,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public class SubmitMessageStub : ISubmitMessage
{
    public void Submit (string username, string password, ref byte[] message)
    {
        // ??? 
    }
}
&lt;/pre&gt;&lt;br /&gt;
our test method expects a contract we can mock,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a mock-friendly "normalized" version of original interface
public interface ISubmitMessageMock
{
    // similar signature to source method ISubmitMessage.Submit,
    // note new response object,
    SubmitResponse Submit (string username, string password, byte[] message);

    // new response class, a super-set of data expected to be 
    // returned
    public class SubmitResponse
    {
        // contains return message value
        public byte[] Message { get; set; }
    }
}
&lt;/pre&gt;&lt;br /&gt;
Jumping back to our consumer, it is a relatively trivial matter to transform from original to mock interface&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public class SubmitMessageStub : ISubmitMessage
{

    // simple constructor that accepts a mock-friendly implementation
    private readonly ISubmitMessageMock _mock = null;
    public SubmitMessageStub (ISubmitMessageMock mock)
    {
        _mock = mock;
    }

    public void Submit (string username, string password, ref byte[] message)
    {
        // NOTE: do NOT add any additional parameter checking
        // or verification. our responsibility is to perform a
        // transform and delegate, let expectation testing occur
        // in caller,

        // 1. transform to mock
        ISubmitMessageMock.SubmitResponse response = _mock.
            Submit (username, password, message);
        // 2. reverse-transform
        message = response.Message;
    }
}
&lt;/pre&gt;&lt;br /&gt;
Our test setup now looks like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;[TestMethod]
public void Test_Process()
{
    Mock&amp;lt;ISubmitMessageMock&amp;gt; serviceMock =
        new Mock&amp;lt;ISubmitMessageMock&amp;gt; (MockBehavior.Strict);

    // proper setup, you can do this with Moq!
    string username = "some.username";
    string password = "some.password";
    byte[] message = null;

    // we control out parameters here through internal
    // response object
    ISubmitMessageMock.SubmitResponse serviceMockResponse =
        new ISubmitMessageMock.SubmitResponse 
        {
            Message = new byte[] { 1, }, 
        };

    serviceMock.

        // we control in parameters here through standard
        // Moq inspection
        Setup (s =&gt; s.Submit (username, password, message)).
        Returns (serviceMockResponse);

    SubmitAdapter adapter = new SubmitAdapter ();

    // simply wrap mock-friendly version with our stub!
    adapter.Process (new SubmitMessageStub (serviceMock.Object));

    // and finally verify service interactions!
    serviceMock.VerifyAll ();
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-5784889025498700800?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5784889025498700800'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5784889025498700800'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/09/unit-testing-how-do-i-mock-signature.html' title='Unit testing, how do I mock a signature with ref or out?'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-1884529391479739636</id><published>2010-07-14T10:12:00.000-07:00</published><updated>2010-07-14T10:52:30.614-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='dependency'/><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='singleton'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, how do I unit test a Singleton?</title><content type='html'>Well, as with our &lt;a href="http://jwgerula.blogspot.com/2010/04/unit-testing-how-do-i-unit-test_07.html"&gt;WebService client&lt;/a&gt;&amp;nbsp;sample, this question is a misnomer. More often than not we are interested in unit testing &lt;em&gt;consumers&lt;/em&gt; of a Singleton than unit testing a Singleton's functional set - and depending on implementation, this may not be as straightforward as we think.&lt;br /&gt;
&lt;br /&gt;
Consider&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a fairly typical Data Access Layer implementation (DAL). have actually
// encountered this on-site [shudders].
public static class DatabaseConnectionFactory
{
    public static IDbConnection GetDatabaseConnection ()
    {
        // 1. get connection string from config
        string connectionString = null;

        // 2. create connection
        SqlConnection connection = null;
        connection = new SqlConnection (connectionString);
        connection.Open ();

        // 3. some other custom stuff
        // 4. return connection
        return connection;
    }

    public static IDbCommand GetDatabaseCommand (
        string commandString,
        IDbConnection connection)
    {
        // 1. set custom stuff like transaction and timeout
        // 2. return command
        return new SqlCommand (commandString, connection);
    }
}

// embedded DAL logic in business tier - anyone else vomit in their 
// mouth just a little? - however what is especially offensive is the
// direct calls to data tier via static class DatabaseConnectionFactory
public class AppointmentBusinessObject
{
    public const string CommandString_LoadById_OneParameter = 
@"SELECT * 
FROM Appointments 
WHERE AppointmentId = {0}";

    public void LoadById (long appointmentId)
    {
        // 1. create Sql command string,
        string commandString = 
            string.Format (
            CommandString_LoadById_OneParameter,
            appointmentId);

        try
        {
            // 2. get connection,
            IDbConnection connection = 
                DatabaseConnectionFactory.
                GetDatabaseConnection ();

            // 3. get command,
            IDbCommand command = 
                DatabaseConnectionFactory.
                GetDatabaseCommand (commandString, connection);

            // 4. execute command
            Reader reader = command.ExecuteReader ();

            // 5. read contents
        }
        finally
        {
            // 6. close connection,
            if (connection != null) 
            {
                connection.Close ();
            }
        }

    }

}
&lt;/pre&gt;&lt;br /&gt;
Now, there are &lt;em&gt;many&lt;/em&gt; reasons why this is a poor design, not the least of which is that we are locked into a single connection and&amp;nbsp;a single implementation. We are forced to duplicate this source if any of these parameters need to change - and believe me this has happened!&lt;br /&gt;
&lt;br /&gt;
If this were not reason enough to contemplate a complete revision, our ability to unit test is also impaired. Specifically, we cannot unit test or verify LoadById without hitting a datastore! In fact, we cannot unit test &lt;em&gt;any class or method that invokes LoadById&lt;/em&gt; without hitting a datastore.&lt;br /&gt;
&lt;br /&gt;
So what can we do?&lt;br /&gt;
&lt;br /&gt;
Well the first thing to do is identify the actual problem - and here it appears to be a tight coupling between our business and data tiers. If we were to abstract DatabaseConnectionFactory then the result would be a loosely-coupled and more flexible system. To this end, I would suggest introducing an interface (that defines DatabaseConnectionFactory's existing members) and consuming this wherever possible.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a simple data store interface, exposes full functional set
// of existing DatabaseConnectionFactory
public interface IDatabaseConnectionFactory
{
    IDbConnection GetDatabaseConnection ();
    IDbCommand GetDatabaseCommand (
        string commandString, 
        IDbConnection connection);
}

// we want this to be as low-impact as possible, so new
// interface defines members that already exist. sadly, 
// static classes cannot implement interfaces directly, 
// and so DatabaseConnectionFactory must be made an instance 
// class. while this requires a little deft maneuvering, 
// this may be accomplished with *zero* impact to existing 
// consumers! yay!
//
// 1. remove static key word from class declaration, this makes
// class instance-based
public class DatabaseConnectionFactory : IDbConnectionFactory
{

    // 2. remove static key word from members, this simply
    // makes existing method implementations instance-based
    public IDbConnection GetDatabaseConnection () { ... }
    public IDbCommand GetDatabaseCommand (
        string commandString,
        IDbConnection connection) { ... }

    // 3. define *new* static members that delegate to
    // instance-based members, this ensures that existing 
    // consumers do not break
    public static IDbConnection GetDatabaseConnection ()
    {
        // instantiate new factory every call for clarity,
        // potential optimization in declaring a static
        // lazy-loaded instance member, and delegating
        // to that instead
        DatabaseConnectionFactory factory = 
            new DatabaseConnectionFactory ();
        return factory.GetDatabaseConnection ();
    }
    public static IDbCommand GetDatabaseCommand (
        string commandString,
        IDbConnection connection) 
    {
        DatabaseConnectionFactory factory = 
            new DatabaseConnectionFactory ();
        return factory.GetDatabaseCommand (commandString, connection);
    }
}

// embedded DAL logic in business tier - vomitting just a little less -
// less offensive now we reference implementation-independent datastore
// definition
public class AppointmentBusinessObject
{
    // still tightly coupled to Sql-compliant datastore
    // but manageable.
    public const string CommandString_LoadById_OneParameter = 
@"SELECT * 
FROM Appointments 
WHERE AppointmentId = {0}";

    // 1. declare new factory member. this is our *dependency*
    // it *must* be fulfilled for class to operate successfully
    private readonly IDbConnectionFactory _factory = null;

    // 2. expose new parameter constructor, permitting consumers
    // of *this* class to specify an appropriate datastore
    public AppointmentBusinessObject (IDbConnectionFactory factory)
    {
        _factory = factory;
    }

    // 3. expose new parameterless constructor, this preserves
    // existing consumers who may not be "up to speed" regarding
    // this new-fangled connection specification. we also preserve
    // previous operating expectations by defaulting to ... 
    // "default" connection factory, so at worst, we deliver
    // *EXACTLY* same behaviour as before
    public AppointmentBusinessObject ()
        : this (new DatabaseConnectionFactory ())
    {
    }

    // 4. consume!
    public void LoadById (long appointmentId)
    {
        // ...
        try
        {
            IDbConnection connection = 
                _factory.GetDatabaseConnection ();
            IDbCommand command = 
                _factory.GetDatabaseCommand (commandString, connection);
            // ...
        }
        finally
        {
            // ...
        }
    }

}
&lt;/pre&gt;&lt;br /&gt;
So, where is the payoff exactly? Well, for one if we now wish to change datastore implementation (say to a MySql, or Oracle, or some other Sql-compliant datastore) we implement a new class and may swap between the two when desired. We also gain the ability to load objects from two or more datastores at the same time!&lt;br /&gt;
&lt;br /&gt;
As a pleasant side-effect, we are also able to unit test LoadById directly, and any consumers that permit datastore specification.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// test business logic without hitting datastore! yay!
[TestMethod]
public void Test_LoadById ()
{
    IDbConnectionFactory mockFactory = null;
    // instantiate mock with expectations
    AppointmentBusinessObject appointment = 
        new AppointmentBusinessObject (mockFactory);
    appointment.LoadById (1024);
    // verify results
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-1884529391479739636?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/1884529391479739636'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/1884529391479739636'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/07/unit-testing-how-do-i-unit-test.html' title='Unit testing, how do I unit test a Singleton?'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-3017755506588562879</id><published>2010-07-09T11:05:00.000-07:00</published><updated>2010-07-12T13:10:08.546-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='dependency'/><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='separation of concern'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><category scheme='http://www.blogger.com/atom/ns#' term='WCF'/><title type='text'>Unit testing, how do I unit test a WCF Service with dependency OperationContext?</title><content type='html'>Unit testing WCF Services is a lot like testing Web Services, especially in that they represent remote business logic. However, in some cases testing may not be straightforward, such as when referencing static framework class OperationContext,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a simple subscription based service.
[ServiceContract (CallbackContract = typeof (ISubscriberCallback))]
public interface ISubscriptionService
{
    // push a subject to service
    [OperationContract]
    void Publish (string subject);

    // subscribe client to publications.
    [OperationContract]
    void Subscribe ();

    // unsubscribe client from publications.
    [OperationContract]
    void Unsubscribe ();
}

// a simple client-side subscription callback.
public interface ISubscriberCallback
{
    // push a subject to subscribers
    [OperationContract]
    void Receive (string subject);
}

// a possible implementation of subscription service
[ServiceBehavior (
    ConcurrencyMode = ConcurrencyMode.Multiple, 
    InstanceContextMode = InstanceContextMode.Single)]
public class SubscriptionService : ISubscriptionService
{

    private readonly object _syncRoot = new object ();
    private readonly List&amp;lt;ISubscriberCallback&amp;gt; _subscribers = 
        new List&amp;lt;ISubscriberCallback&amp;gt; ();

    public void Publish (string subject) { ... }

    public void Subscribe ()
    {
        // hm, static framework references ... 
        ISubscriberCallback subscriber = 
            OperationContext.
            Current.
            GetCallbackChannel&amp;lt;ISubscriberCallback&amp;gt; ();

        lock (_syncRoot)
        {
            if (!_subscribers.Contains (subscriber))
            {
                _subscribers.Add (subscriber);
            }
        }
    }

    public void Unsubscribe () { ... }

}
&lt;/pre&gt;&lt;br /&gt;
Unfortunately, if our service implements some sophisticated business logic while initializing callbacks then we risk either losing coverage with no tests or losing time and resources on elaborate environments to support our integration into WCF framework.&lt;br /&gt;
&lt;br /&gt;
Well not to fear, this is strikingly familiar to our &lt;a href="http://jwgerula.blogspot.com/2010/04/unit-testing-how-do-i-unit-test.html"&gt;Web Service with Context dependency&lt;/a&gt;, and I would proscribe a similar solution. Namely,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a simple abstraction to separate our business from 
// WCF framework. depending on our requirements, could be
// general for re-use elsewhere in our application code,
// or specific if this is a one-off use.
public interface IOperationContext
{
    // add methods as needed, for now we definitely
    // need access to our callbacks!
    CType GetCallbackChannel&amp;lt;CType&amp;gt; ();
}

// a simple wrapper implementation of operation context
public class OperationContextCurrent : IOperationContext
{
    public CType GetCallbackChannel&amp;lt;CType&amp;gt; ()
    {
        return OperationContext.
            Current.
            GetCallbackChannel&amp;lt;CType&amp;gt; ();
    }
}

[ServiceBehavior (
    ConcurrencyMode = ConcurrencyMode.Multiple, 
    InstanceContextMode = InstanceContextMode.Single)]
public class SubscriptionService : ISubscriptionService
{

    private readonly IOperationContext _context = null;
    private readonly object _syncRoot = new object ();
    private readonly List&amp;lt;ISubscriberCallback&amp;gt; _subscribers = 
        new List&amp;lt;ISubscriberCallback&amp;gt; ();

    // inject our dependency on operation context! this
    // decoupling actually makes sense - if we swap 
    // transport stacks we just require an implementation
    // that returns our requested callbacks!
    public SubscriptionService (IOperationContext context)
    {
        _context = context;
    }

    public void Subscribe ()
    {
        // ... ahhhh, that's much better!
        ISubscriberCallback subscriber = 
            _context.
            GetCallbackChannel&amp;lt;ISubscriberCallback&amp;gt; ();

        lock (_syncRoot)
        {
            if (!_subscribers.Contains (subscriber))
            {
                _subscribers.Add (subscriber);
            }
        }
    }

}
&lt;/pre&gt;&lt;br /&gt;
Now, if we were so inclined to test Subscribe above,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// test business logic without WCF! yay!
[TestMethod]
public void Test_Subscribe ()
{
    IOperationContext mockContext = null;
    // instantiate mock with expectations
    SubscriptionService service = new SubscriptionService (mockContext);
    service.Subscribe ();
    // verify results
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-3017755506588562879?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/3017755506588562879'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/3017755506588562879'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/07/unit-testing-how-do-i-unit-test-wcf.html' title='Unit testing, how do I unit test a WCF Service with dependency OperationContext?'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-5723200499681055526</id><published>2010-07-05T12:21:00.000-07:00</published><updated>2010-07-07T10:51:27.428-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='framework'/><category scheme='http://www.blogger.com/atom/ns#' term='chess'/><category scheme='http://www.blogger.com/atom/ns#' term='concurrency test'/><title type='text'>Concurrency testing, viva CHESS!</title><content type='html'>A quick blip on the radar! &lt;a href="http://stackoverflow.com/questions/3179640/multithread-debugging-techniques/3179737#3179737"&gt;I was just recently made aware&lt;/a&gt; of a (conceptually)&amp;nbsp;&lt;a href="http://research.microsoft.com/en-us/projects/chess/"&gt;awesome framework for exercising concurrent code&lt;/a&gt;. I have yet to employ CHESS myself but I am excited by &lt;a href="ftp://ftp.research.microsoft.com/pub/tr/TR-2007-149.pdf"&gt;its many promises&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-5723200499681055526?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5723200499681055526'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5723200499681055526'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/07/concurrent-testing-viva-chess.html' title='Concurrency testing, viva CHESS!'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-6203456235624703744</id><published>2010-07-05T12:11:00.000-07:00</published><updated>2010-07-07T10:50:35.507-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='integration test'/><category scheme='http://www.blogger.com/atom/ns#' term='production'/><category scheme='http://www.blogger.com/atom/ns#' term='user acceptance test'/><category scheme='http://www.blogger.com/atom/ns#' term='quality assurance'/><category scheme='http://www.blogger.com/atom/ns#' term='manual test'/><category scheme='http://www.blogger.com/atom/ns#' term='automated test'/><category scheme='http://www.blogger.com/atom/ns#' term='system integration test'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><category scheme='http://www.blogger.com/atom/ns#' term='system test'/><category scheme='http://www.blogger.com/atom/ns#' term='preproduction'/><title type='text'>Testing, types, kinds, and flavours</title><content type='html'>Building on &lt;a href="http://jwgerula.blogspot.com/2010/05/testing-anatomy-of-test.html"&gt;anatomy of a test&lt;/a&gt;, I would like to follow up with a few points of note. These points are not based on any academic theory, principle, or practice. Instead, they are based mostly on anecdotal experience - so do not take this as "law", but rather a practical framework for communicating expectations about "testing" in general.&lt;br /&gt;
&lt;br /&gt;
Preface aside, these points may be separated into three independent aspects,&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Types,&lt;/li&gt;
&lt;li&gt;Kinds, and&lt;/li&gt;
&lt;li&gt;Environments,&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;strong&gt;Types&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
There are three main types of tests; unit tests, integration tests, and system tests. What differentiates one type of test from another is scope.&lt;br /&gt;
&lt;br /&gt;
A unit test evaluates functional behaviour of a single component - all dependencies are stubbed or appropriately mocked. An integration test evaluates functional integration of two or more components - dependencies outside of a chosen scope are stubbed or mocked. A system test is a special case of an integration test, it evaluates functional behaviour of all components - no dependency is stubbed or mocked.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Kinds&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Every test is carried out in one of two fashions, a test is either manual or automated. Admittedly, such a small set hardly warrants discussion, but it is important to recognize this distinction. Even if, as developers, we deal primarily in automated tests it may sometimes fall to us to provide a manual test plan for person-in-seat testers.&lt;br /&gt;
&lt;br /&gt;
In terms of resources required, execution times, and result variance, manual tests may differ significantly from an automated equivalent. As such, it is important to understand these differences, and communicate appropriate expectations regarding the work required by that kind of test.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Environments&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
Last and not least is the environment in which a test executes. The shape of data used as input may impact veracity and performance* of a test, which is why it is important to implement and maintain different testing stages thoughout a development cycle.&lt;br /&gt;
&lt;br /&gt;
The point and purpose of each stage is twofold. First, each distinct stage&amp;nbsp;we implement should progress from&amp;nbsp;development-ready quality to production-ready quality. Second, each stage isolates itself from the other - and we do not promote code if it does not pass muster.&lt;br /&gt;
&lt;br /&gt;
As an example, we may have several development environments (one for each developer!), a single build environment, a Quality Assurance (QA) environment, a System Integration Test (SIT) environment,&amp;nbsp;a User Acceptance Test (UAT) environment, and a Preproduction Test (PreProd or PPT) environment.&lt;br /&gt;
&lt;br /&gt;
This is certainly not exhaustive, just some of the common stages I have seen in my work.&lt;br /&gt;
&lt;br /&gt;
Perhaps we noticed that one environment is conspicuously absent? That would be Production (Prod). We do not typically test in Prod. In fact, &lt;em&gt;never&lt;/em&gt; test in Prod. PreProd&amp;nbsp;&lt;em&gt;is&lt;/em&gt; an exact mirror, from hardware to data to security infrastructure. Furthermore, the &lt;em&gt;only&lt;/em&gt; distinction between PreProd and Prod is that PreProd is &lt;em&gt;not&lt;/em&gt; Prod. This speaks most importantly to the second point and purpose above, isolation. Heaven forbid anything goes wrong at this stage, but &lt;em&gt;if it does&lt;/em&gt; then Prod is safe and we dodge the million dollar liability suit/bullet.&lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Further reading&lt;/strong&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;a href="http://en.wikipedia.org/wiki/Software_testing"&gt;Wikipedia on testing.&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* = hm, some may be confused by my citing "performance" here. Generally speaking, performance testing is treated distinctly from functional testing and we do not mix the two. However, from a perspective of "testing", each sets expectations, invokes a process, and evaluates outcomes to expectations, and so performance is as valid a quality as a functional outcome in this context.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-6203456235624703744?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/6203456235624703744'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/6203456235624703744'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/07/testing-types-kinds-and-flavours.html' title='Testing, types, kinds, and flavours'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-888928843261876844</id><published>2010-05-13T07:01:00.000-07:00</published><updated>2010-07-07T10:46:24.235-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='design'/><category scheme='http://www.blogger.com/atom/ns#' term='test'/><category scheme='http://www.blogger.com/atom/ns#' term='fundamental'/><title type='text'>Testing, anatomy of a test</title><content type='html'>Hm, just firing off a quick post here - the basic structure of a test &lt;br /&gt;
&lt;ol&gt;&lt;li&gt;Set expectations,&lt;/li&gt;
&lt;li&gt;Perform test and record actuals, and&lt;/li&gt;
&lt;li&gt;Evaluate actuals against expectations&lt;/li&gt;
&lt;/ol&gt;Seems kind of trite and silly to state the obvious, but whenever I find myself in a bind it helps to take things back to basics.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-888928843261876844?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/888928843261876844'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/888928843261876844'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/05/testing-anatomy-of-test.html' title='Testing, anatomy of a test'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-5217782193356224827</id><published>2010-04-07T11:20:00.000-07:00</published><updated>2010-07-07T10:45:33.791-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='webservice client'/><category scheme='http://www.blogger.com/atom/ns#' term='separation of concern'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, how do I unit test WebService client X?</title><content type='html'>Another scenario I commonly encounter is the &lt;a href="http://stackoverflow.com/questions/1615093/how-to-mock-a-web-service/1615677#1615677"&gt;client side component&lt;/a&gt;&amp;nbsp;to a WebService-based design.&lt;br /&gt;
&lt;br /&gt;
For example,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a client side view, displaying 
// server side profile data
public partial class ProfileView : UserControl
{
    private readonly Session _session = null;

    public ProfileViewModel ViewModel 
    {
        get { return (ProfileViewModel)(DataContext); }
        set { DataContext = value; } 
    }

    public ProfileView ()
    {
        InitializeComponent ();
    }

    // command implementation, fetches and assigns server side
    // data to client side data model
    public void Command_RefreshProfile ()
    {
        // embedded transmission codes! tsk tsk tsk
        // 
        // 1. get profile service
        ProfileWebService service = new ProfileWebService ();
        // 2. get profile
        Profile profile = service.GetProfile (_session);
        // 3. map to client side model
        ViewModel = new ProfileViewModel (profile);
    }
}
&lt;/pre&gt;&lt;br /&gt;
which is typical of a thick WPF client. Now, first thing to note is that the question&lt;br /&gt;
&lt;blockquote&gt;&lt;em&gt;how do I unit test WebService client X?&lt;/em&gt;&lt;/blockquote&gt;is a bit of a misnomer. We are not actually interested in unit testing our WebService client, or in this case an instance of ProfileWebService. As with our &lt;a href="http://jwgerula.blogspot.com/2010/03/unit-testing-how-do-i-unit-test.html"&gt;WebService example&lt;/a&gt;&amp;nbsp;what we really want to do is test our business logic and &lt;em&gt;only&lt;/em&gt; our business logic.&lt;br /&gt;
&lt;br /&gt;
Similarly then, the solution to this problem is to isolate our business from our remote invocation,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a formal contract, defining all public operations 
// available for profile service
public class IProfileService
{
    Profile GetProfile (Session session);
}

public partial class ProfileView : UserControl
{
    private readonly Session _session = null;
    private readonly IProfileService _service = null;

    public ProfileViewModel ViewModel { get; set; }

    // we now pass in a reference to an implementation of our
    // profile service contract
    public ProfileView (IProfileService service)
    {
        InitializeComponent ();

        _service = service;
    }

    public void Command_RefreshProfile ()
    {
        // no embedded transmission codes! ah, nice clean code
        Profile profile = _service.GetProfile (_session);
        ViewModel = new ProfileViewModel (profile);
    }
}
&lt;/pre&gt;&lt;br /&gt;
When it comes to implementing IProfileService, we have one of two choices. If we are really lazy, and have access to the WebReference source,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// auto-generated web reference. except for these
// comments. and IProfileService definition below.
public partial class ProfileWebService : 
    System.Web.Services.Protocols.SoapHttpClientProtocol, 
    IProfileService
{
    // ...
}    
&lt;/pre&gt;&lt;br /&gt;
This has the advantage of no additional overhead or extraneous source files. The down-side is that maintenance is at a premium if the WebReference ever changes - which happens quite often in development. We must always remember to locate and modify the auto-generated classes with this interface definition!&lt;br /&gt;
&lt;br /&gt;
Now, an alternative may be to automate the modification process, however that sounds like a lot of work to me. I would rather go the other route, and again, abstract the implementations a little.&lt;br /&gt;
&lt;br /&gt;
Consider then,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a thin wrapper for our auto-generated classes.
// has advantage of referencing most current web 
// reference when updated, without breaking existing 
// consumers
public class ProfileServiceProxy : IProfileService
{
    #region IProfileService Members

    // very simple pass through to actual auto-generated
    // implementation
    public Profile GetProfile (Session session)
    {
        // it is very important to keep this bit clean,
        // !!! NO BUSINESS LOGIC !!!
        ProfileWebService service = new ProfileWebService ();
        return service.GetProfile (session);
    }

    #endregion
}
&lt;/pre&gt;&lt;br /&gt;
Whichever route you go with, you have successfully isolated business from our remote service. This has the added advantage of being able to swap out ProfileServiceProxy with any implementation we like, say a WCF client, or a local instance of the actual service!&lt;br /&gt;
&lt;br /&gt;
Our unit tests also benefit,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;[TestMethod] 
public void Test_Command_RefreshProfile () 
{ 
    Session session = new Session ();

    IProfileService mockService = null;
    // instantiate mock with expectations 
    ProfileView view = new ProfileView (mockService); 
    view.Command_RefreshProfile (); 
    // verify results 
} 
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-5217782193356224827?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5217782193356224827'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5217782193356224827'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/04/unit-testing-how-do-i-unit-test_07.html' title='Unit testing, how do I unit test WebService client X?'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-4494022803502686752</id><published>2010-04-07T06:55:00.000-07:00</published><updated>2010-07-07T10:44:35.853-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='dependency'/><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='webservice'/><category scheme='http://www.blogger.com/atom/ns#' term='separation of concern'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, how do I unit test WebService X with dependency Y?</title><content type='html'>Before moving on, I would like to build on our &lt;a href="http://jwgerula.blogspot.com/2010/03/unit-testing-how-do-i-unit-test.html"&gt;WebService example&lt;/a&gt;. In that example, we separated our business logic from our hosting solution. However, it may occur that our source solution has dependencies that must be fulfilled.&lt;br /&gt;
&lt;br /&gt;
Consider this modified example,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a profile web service, represents business logic 
// hosted from a web service
public class ProfileWebSevice : System.Web.Services.WebService
{

    // gets a profile for remote client
    [WebMethod]
    public Profile GetProfile (Session session)
    {
        Profile profile = null;

        // obtain authentication service from
        // web service context
        AuthenticationService auth = 
            (AuthenticationService)(Context.Cache["auth"]);

        // embedded business logic, bad bad bad
        // 
        // 1. authenticate
        if (auth.IsAuthenticated (session))
        {
            // 2. create sql connection
            // 3. get profile
            // 4. populate profile
            profile = new Profile (dataReader);
        }

        return profile;
    }

}&lt;/pre&gt;&lt;br /&gt;
Note the dependency introduced by member variable Context. If we were to perform our simple refactor, we introduce compile-time issues,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public class ProfileService  
{ 
    public Profile GetProfile (Session session) 
    { 
        // COMPILE-ERROR: "Context" does not exist here! oh nos!!!
        AuthenticationService auth = 
            (AuthenticationService)(Context.Cache["auth"]);
        // ...
    } 
}&lt;/pre&gt;&lt;br /&gt;
Fortunately, the solution is fairly straightforward. The key is realising our business logic of authenticate, fetch, instantiate is completely separate from the services that facilitate it. Our business class is a &lt;em&gt;consumer&lt;/em&gt; of these services. From this perspective, it seems obvious to request these services as part of our invocation.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public class ProfileService  
{ 
    public Profile GetProfile (AuthenticationService auth, Session session) 
    {
        if (auth.IsAuthenticated (session)) { ... }
        // ...
    }
}&lt;/pre&gt;&lt;br /&gt;
and our WebService now looks like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public class ProfileWebSevice : System.Web.Services.WebService
{
    [WebMethod]
    public Profile GetProfile (Session session)
    {
        AuthenticationService auth = 
            (AuthenticationService)(Context.Cache["auth"]);
        ProfileService service = new ProfileService ();
        Profile profile = service.GetProfile (auth, session);
        return profile;
    }
}
&lt;/pre&gt;&lt;br /&gt;
Again, our business logic does not care who or how a service is implemented, only that whomever is doing it, conforms to some known invocation. In this scenario, that an object instance of type AuthenticationService contains a method IsAuthenticated.&lt;br /&gt;
&lt;br /&gt;
Our unit tests may look like&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// test business logic without web service! yay! 
[TestMethod] 
public void Test_GetProfile_NullSession () 
{ 
    AuthenticationService auth = new AuthenticationService ();
    ProfileService service = new ProfileService (); 
    Profile actual = service.GetProfile (auth, null);
    // verify profile expectations
    // verify authentication service expectations
}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-4494022803502686752?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/4494022803502686752'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/4494022803502686752'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/04/unit-testing-how-do-i-unit-test.html' title='Unit testing, how do I unit test WebService X with dependency Y?'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-8126765952793853308</id><published>2010-04-01T13:28:00.000-07:00</published><updated>2010-10-13T06:07:33.549-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='humour'/><category scheme='http://www.blogger.com/atom/ns#' term='heart'/><category scheme='http://www.blogger.com/atom/ns#' term='stack overflow'/><category scheme='http://www.blogger.com/atom/ns#' term='joke'/><category scheme='http://www.blogger.com/atom/ns#' term='unicorn'/><category scheme='http://www.blogger.com/atom/ns#' term='funny'/><category scheme='http://www.blogger.com/atom/ns#' term='rainbow'/><category scheme='http://www.blogger.com/atom/ns#' term='april fool'/><title type='text'>I &lt;3 unicorns ...</title><content type='html'>Happy April Fool's everyone! Loving the rainbow-y goodness of Stack Overflow's humour!&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://1.bp.blogspot.com/_24VPmXFKcCg/S7UBI1O6EfI/AAAAAAAAAAM/ICx1-L24zv4/s1600/iHeartUnicorns.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"&gt;&lt;img border="0" height="211" nt="true" src="http://1.bp.blogspot.com/_24VPmXFKcCg/S7UBI1O6EfI/AAAAAAAAAAM/ICx1-L24zv4/s400/iHeartUnicorns.png" width="400" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-8126765952793853308?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/8126765952793853308'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/8126765952793853308'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/04/i-unicorns.html' title='I &amp;lt;3 unicorns ...'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://1.bp.blogspot.com/_24VPmXFKcCg/S7UBI1O6EfI/AAAAAAAAAAM/ICx1-L24zv4/s72-c/iHeartUnicorns.png' height='72' width='72'/></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-5435847638691543208</id><published>2010-03-19T11:10:00.000-07:00</published><updated>2010-07-07T10:39:51.881-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='webservice'/><category scheme='http://www.blogger.com/atom/ns#' term='stack overflow'/><category scheme='http://www.blogger.com/atom/ns#' term='separation of concern'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, how do I unit test WebService X?</title><content type='html'>Most of this article appears in a &lt;a href="http://stackoverflow.com/"&gt;StackOverflow&lt;/a&gt; &lt;a href="http://stackoverflow.com/questions/1615093/how-to-mock-a-web-service/1615677#1615677"&gt;post&lt;/a&gt; I submitted some time ago.&lt;br /&gt;
&lt;br /&gt;
As the first bit of meat we cover in this series, we have a fairly typical scenario.&lt;br /&gt;
&lt;blockquote&gt;&lt;em&gt;How do I unit test WebService X?&lt;/em&gt;&lt;/blockquote&gt;This scenario often presents itself as a WebService with embedded business logic within it.&lt;br /&gt;
&lt;br /&gt;
For example&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a profile web service, represents business logic 
// hosted from a web service
public class ProfileWebSevice : System.Web.Services.WebService
{

    // gets a profile for remote client
    [WebMethod]
    public Profile GetProfile (Session session)
    {
        Profile profile = null;

        // embedded business logic, bad bad bad
        // 
        // 1. authenticate
        AuthenticationService auth = new AuthenticationService ();
        if (auth.IsAuthenticated (session))
        {
            // 2. create sql connection
            // 3. get profile
            // 4. populate profile
            profile = new Profile (dataReader);
        }

        return profile;
    }

}
&lt;/pre&gt;&lt;br /&gt;
I have worked on a number of web-based systems that employ this pattern, or something very similar. The four steps performed in sequence represent a very specific business flow, and it is not at all unreasonable to expect this flow to be tested.&lt;br /&gt;
&lt;br /&gt;
Unfortunately, our example does not lend itself to testing very easily. For one, anyone reviewing this source would have difficulty separating our business from service hosting. While this distinction may seem trivial, it is often a source of great confusion. Do we need to host ProfileWebService? What about client-side proxies? Should we invoke from a web-client?&lt;br /&gt;
&lt;br /&gt;
In short, the answer is no. WebProfileService and GetProfile represent parts of another tier altogether, that of web service hosting - and as far as testing is concerned, we are completely uninterested in testing [what is essentially] a third party hosting solution. Ultimately, we are interested in exercising our business logic and &lt;em&gt;only&lt;/em&gt; our business logic.&lt;br /&gt;
&lt;br /&gt;
What we really want is something like,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// a profile service without web service hosting,
public class ProfileService  
{ 

    // gets a profile
    public Profile GetProfile (Session session) 
    { 
        Profile profile = null;

        // 1. authenticate
        AuthenticationService auth = new AuthenticationService ();
        if (auth.IsAuthenticated (session))
        {
            // 2. create sql connection
            // 3. get profile
            // 4. populate profile
            profile = new Profile (dataReader);
        }

        return profile;
    } 
}&lt;/pre&gt;&lt;br /&gt;
which is &lt;em&gt;completely &lt;/em&gt;free of any web service tom-foolery. Our web service then looks like,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// this web service is now a consumer of a business class, 
// no embedded logic, so does not require direct testing 
public class ProfileWebSevice : System.Web.Services.WebService
{

    [WebMethod]
    public Profile GetProfile (Session session)
    {
        ProfileService service = new ProfileService ();
        Profile profile = service.GetProfile (session);
        return profile;
    }

}
&lt;/pre&gt;&lt;br /&gt;
Finally, to test our re-imagined service,&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;// test business logic without web service! yay! 
[TestMethod] 
public void Test_GetProfile_NullSession () 
{ 
    ProfileService service = new ProfileService (); 
    Profile actual = service.GetProfile (null);
    // verify results 
}
&lt;/pre&gt;&lt;br /&gt;
Making your WebMethods simple passthroughs to proper underlying business classes and removing logic from them completely, allows you to target "real" user code as opposed to the plumbing of your typical WebService implementation.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-5435847638691543208?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5435847638691543208'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/5435847638691543208'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/03/unit-testing-how-do-i-unit-test.html' title='Unit testing, how do I unit test WebService X?'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-3552946171789183631</id><published>2010-03-19T07:21:00.000-07:00</published><updated>2010-07-07T10:42:29.210-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='code format test'/><title type='text'>Code fragment</title><content type='html'>Hello all, just testing new code formatting&lt;br /&gt;
&lt;br /&gt;
&lt;pre class="brush: csharp"&gt;public class SomeClass : ISomeInterface
{

    public SomeClass ( ) { }

    // interfaces

    #region ISomeInterface Members

    public void SomeWork ()
    {
    }

    #endregion

}
&lt;/pre&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-3552946171789183631?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/3552946171789183631'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/3552946171789183631'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/03/code-fragment.html' title='Code fragment'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-6739867383245163782</id><published>2010-02-18T10:45:00.000-08:00</published><updated>2010-07-07T10:41:33.332-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='interface programming'/><category scheme='http://www.blogger.com/atom/ns#' term='encapsulation'/><category scheme='http://www.blogger.com/atom/ns#' term='design'/><category scheme='http://www.blogger.com/atom/ns#' term='separation of concern'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, better design</title><content type='html'>Ahem, so before we dig into some code, I would like to take a minute and say something.&lt;br /&gt;
&lt;br /&gt;
I can be a very stubborn and obstinate person, and I am also incredibly lazy! As such, even having attended many lectures and throwing thousands and thousands of dollars at some of the finest academia, I ignored many of the simple, basic, fundamental principles of Computing they tried to instill in me.&lt;br /&gt;
&lt;br /&gt;
Principles like&lt;br /&gt;
&lt;ol&gt;&lt;li&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/aa260635(VS.60).aspx"&gt;Interface programming&lt;/a&gt;,&lt;/li&gt;
&lt;li&gt;&lt;a href="http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)"&gt;Encapsulation&lt;/a&gt;,&lt;/li&gt;
&lt;li&gt;&lt;a href="http://en.wikipedia.org/wiki/Separation_of_concerns"&gt;Separation of Concern&lt;/a&gt; [SoC],&lt;/li&gt;
&lt;/ol&gt;I am positive there are more, but these three form a triad of sorts, themes in my most recent adventures.&lt;br /&gt;
&lt;br /&gt;
This sad state of ignorance was further compounded by youth, inexperience, and entering the "real world", where constraints prohibited my ability to exercise these principles.&lt;br /&gt;
&lt;br /&gt;
Many, many, many years later, after much trial, error, and tribulation I have entered something of a personal [and professional!] renaissance. Rediscovering some of these principles, I am continually finding new ways to &lt;em&gt;simplify&lt;/em&gt;, &lt;em&gt;extend&lt;/em&gt;, and &lt;em&gt;robustify&lt;/em&gt; [alright, that is not really a word, but whatever] my work.&lt;br /&gt;
&lt;br /&gt;
If that were not enough, then may I also add: Applying these simple yet powerful principles facilitates unit testing! Yes! That is right! Not only will you produce better work, but you will be able to quantitatively and qualitatively &lt;em&gt;prove&lt;/em&gt; it is better.&lt;br /&gt;
&lt;br /&gt;
If you are not yet sold, I do ask that you continue reading. Certainly, for the attentive reader, you will see these three principles come up time and time again in the [real world!] examples I present.&lt;br /&gt;
&lt;br /&gt;
As I have said, it has taken me a long time to come around and see this for myself. It is my hope here and now, that you benefit from my experience: When designing a functional component, think about how Interfaces, Encapsulation, and SoC can help you. Invariably, such considerations will lead to better design and better product.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-6739867383245163782?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/6739867383245163782'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/6739867383245163782'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2010/02/unit-testing-good-design.html' title='Unit testing, better design'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-1954662273671240331</id><published>2009-11-03T07:26:00.000-08:00</published><updated>2010-07-07T10:41:02.028-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='introduction'/><category scheme='http://www.blogger.com/atom/ns#' term='stack overflow'/><category scheme='http://www.blogger.com/atom/ns#' term='unit test'/><title type='text'>Unit testing, an introduction</title><content type='html'>Browsing &lt;a href="http://stackoverflow.com/"&gt;stack overflow&lt;/a&gt; the other day, I noticed &lt;a href="http://stackoverflow.com/questions/tagged/unit-testing"&gt;quite a few questions regarding unit testing&lt;/a&gt;. I &lt;a href="http://stackoverflow.com/questions/1601073/nunit-mocking-not-working-for-singleton-method/1601438#1601438"&gt;responded&lt;/a&gt; to a &lt;a href="http://stackoverflow.com/questions/1607499/mocking-system-drawing-image-with-moq/1607613#1607613"&gt;few&lt;/a&gt; &lt;a href="http://stackoverflow.com/questions/1615093/how-to-mock-a-web-service/1615677#1615677"&gt;such&lt;/a&gt; &lt;a href="http://stackoverflow.com/questions/1626556/how-can-i-test-a-singleton-class-with-dunit/1626617#1626617"&gt;questions&lt;/a&gt;, but found I repeated myself a bit. I then &lt;a href="http://www.google.ca/search?hl=en&amp;amp;source=hp&amp;amp;q=how+to+unit+test&amp;amp;meta=&amp;amp;aq=f&amp;amp;oq="&gt;took a look around&lt;/a&gt;, and found a lot of resources about testing frameworks and evangelicals in favour of the practice, but precious few conferring advice or guidance in the subject of "how to unit test well".&lt;br /&gt;
&lt;br /&gt;
This has [somewhat] inspired me to write a series of articles about lessons I have learned and experiences I have had in my years as a developer - and hopefully these will help :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-1954662273671240331?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/1954662273671240331'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/1954662273671240331'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2009/11/unit-testing-introduction.html' title='Unit testing, an introduction'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry><entry><id>tag:blogger.com,1999:blog-1322079872927855793.post-151727734906003811</id><published>2009-10-22T13:35:00.001-07:00</published><updated>2010-07-07T10:40:35.664-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='humour'/><category scheme='http://www.blogger.com/atom/ns#' term='hello world'/><category scheme='http://www.blogger.com/atom/ns#' term='joke'/><category scheme='http://www.blogger.com/atom/ns#' term='funny'/><category scheme='http://www.blogger.com/atom/ns#' term='lamorz'/><category scheme='http://www.blogger.com/atom/ns#' term='lame'/><title type='text'>Hello World</title><content type='html'>Hello!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1322079872927855793-151727734906003811?l=jwgerula.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/151727734906003811'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1322079872927855793/posts/default/151727734906003811'/><link rel='alternate' type='text/html' href='http://jwgerula.blogspot.com/2009/10/hello-world.html' title='Hello World'/><author><name>johnny g</name><uri>http://www.blogger.com/profile/08277259909432475021</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author></entry></feed>
