Making WCF Proxy useable

The way WCF proxies are designed is to live until shi* happens.

Let’s assume that we have a CalcualtorService with one method named Divide(int a, int b). Sasha, a cool programmer-dude, trying to produce some usefull software writes:


public MyCalcualtorForm : Form {

   private
CalculatorProxy _calc = new CalculatorProxy();

   Calc_Click(…) {
      _calc.Divide(firstNumber, secondNumber);
   }
}


What is the first error you can think of that could happen? Yep, DivideByZeroException.
Once the proxy gets an exception, it enters into a “Faulted” state which makes the proxy unusable(=you cannot use it again).
The quickest solution is to work “by the book” and create a new instance each and every time we need to call the service:


Calc_Click(…) {
   using (CalculatorProxy calc = new CalculatorProxy())
      calc.Divide(firstNumber, secondNumber);
}


But what’s bad in this solution?



  1. Performance – you pay (not a lot but neither little) for each creation of the proxy. Sure, it will probably not be your bottleneck, but heck, why is it useful? Most of the time the proxy will not throw an exception and yet we need to create it every time just to avoid the faulted state scenario. 
  2. Design – If we declare this exception BY CONTRACT, I would expect that the proxy will still be usable afterwards. Do we really want to return Enum\int\string as status instead of throwing exception just because of poor design?
  3. TDD – you know that I’m in love with it. Now imagine Dependency Injection. Component A recieve ICalculatorProxy and use it to… calculate something. Working “by the book” is no good as we want to recieve an instance of the proxy from the outside in order to mock it. Right, so we inject a proxy from the outside (got to love Windsor) and life is pretty sweeet. Darn! Wait! one poor (even by design) exception and our proxy goes dead. Very un-TDDish of Microsoft.

I had to come with a solution as no one will take TDD away from me. I present to you ProtectedProxy: this little IL-code-at-the-end-of-the-day will able you to recover from faulted state by creating a new proxy on each exception thus making your proxy… useable (couldn’t think about a better word to describe it). Think about a situation where your proxy is trying to call the service but the service is down; In Semingo, we decided that we want to keep trying until the service is up. Via ProtectedProxy, you can determine how many times do you want to recover and when you should finally kill the proxy. Oh yea, ProtectedProxy uses Windsor in order to create new proxies if needed and logging messages to log4net. Good stuff.


In the example above, all Sasha had to do was to:
1). Initialize the _calc field by:
        ProtectedProxy<ICalculatorProxy> _calc = new ProtectedProxy<ICalculatorProxy>(new CalculatorProxy());
2). call _calc via:
        _calc.Instance.Divide(firstNumber, secondNumber);

But enough said, code please:


// Written by Oren Ellenbogen (07.08.07) – trying to protect our proxies so they could recover from:
// (A) The service is not up yet, but we want to try again later.
// (B) The service throws (ANY) exception, we still want our proxy to function (bubble the exception, but still keep on working).
// Microsoft intended to use a NEW proxy per call, but for TDD this is not ideal as we would like to inject proxies from outside as mocks
// in order to simulate multiple scenarios.

#region using

using System;
using System.Reflection;
using System.ServiceModel;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using log4net;

#endregion

namespace Semingo.Services.Proxies.Helpers
{
   
   public interface IProxy : ICommunicationObject { 
      bool Ping();
   }


   /// <summary>
   /// Protect proxy from entering Faulted state by re-creating the proxy via Windsor Container on Faulted.
   /// IMPORTANT: that even if a fatal exception is raised by the service (for example: the service is not up yet), the proxy will be raised again. 
   /// Use it wisely (TIP: you CAN determine the number of ‘recovery’ attempts).

   /// </summary>
   /// <typeparam name=”I”>The proxy interface to protect</typeparam>
   /// <remarks>
   /// The way WCF works is that ANY exception on the service will cause the proxy to enter “faulted” state which means you can not use it anymore.
   /// Imagine a service of CalculatorService that expose the method float Divide(int a, int b). Sending b=0 will raise an exception in the service
   /// and the proxy will get into faulted state. This is not ideal as the proxy itself should be used again.
   /// </remarks>
   public class ProtectedProxy<I> : IDisposable
      where I : IProxy
   {
      private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 

      private I _instance;
      private readonly IWindsorContainer _container;
      private int _faultedCounter = 0;
      private bool _disposed = false;
      private const int AlertableNumberOfFaultedTimes = 10; 

      public ProtectedProxy(I instance)
         : this(CreateXmlBasedWindsorContainer(), instance)
      {   
      } 

      public ProtectedProxy(IWindsorContainer container, I instance)
      {
         _container = container;
         ShieldInstance(instance);
      } 

      /// <summary>
      /// Returns the number of faults this proxy had so far
      /// </summary>
      public int NumberOfFaults
      {
         get { return _faultedCounter; }
      } 

      public I Instance
      {
         get
         {
            ThrowIfInstanceAlreadyDisposed(); 

            if (_instance.State == CommunicationState.Faulted || _instance.State == CommunicationState.Closed || _instance.State == CommunicationState.Closing)
               {
                  _logger.Warn(“Notice: The proxy state is invalid (“ + communicationObj.State + “). The Faulted event should have been raised and handle this state – this need to be checked.”);
                  HandleFaultedInstance();
               }

            return _instance;
         }
      } 

      public void Close()
      {
         Dispose();
      } 

      private void ThrowIfInstanceAlreadyDisposed()
      {
         if (_disposed)
            throw new ObjectDisposedException(“The protected proxy for the type: “ + _instance.GetType().FullName + ” was closed. Cannot return a live instance of this type.”);
      } 

      private void ShieldInstance(I instance)
      {
         _instance = instance; 
         _instance.Faulted += delegate { HandleFaultedInstance(); };
      } 

      private void HandleFaultedInstance()
      {
         ThrowIfInstanceAlreadyDisposed(); 

         _faultedCounter++; 

         if (_faultedCounter >= AlertableNumberOfFaultedTimes)
            _logger.Warn(“ALERT! The proxy for the type “ + _instance.GetType().FullName + ” got faulted for the “ + _faultedCounter + ” time. Recreating the proxy but we must verify if this is valid.”);
         else if (_logger.IsDebugEnabled)
            _logger.Debug(“Proxy for type “ + _instance.GetType().FullName + ” got faulted (current state: “ + ((ICommunicationObject)_instance).State + “) – recreating the proxy. Number of faulted instances so far: “ + _faultedCounter + “.”); 

         ProxyHelper.CloseProxy(_instance); // close current proxy
         ShieldInstance(_container.Resolve<I>()); // re-create the proxy, faulted proxies are no good for further use.
      } 

      private static IWindsorContainer CreateXmlBasedWindsorContainer()
      {
         try
         {
            return new WindsorContainer(new XmlInterpreter(new ConfigResource(“castle”)));
         }
         catch (Exception err)
         {
            _logger.Warn(“Unable to create xml based windsor container, using empty one.”, err);
            return new WindsorContainer(); // for testing (the proxy will be mocked anyway).
         }
      } 

      #region IDisposable Members 

      ///<summary>
      ///Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
      ///</summary>
      public void Dispose()
      {
         Dispose(true);
         GC.SuppressFinalize(this);
      } 

      protected virtual void Dispose(bool disposing)
      {
         _logger.Info(“Attempting to dispose the protected proxy for the type: “ + _instance.GetType().FullName + “, disposed already? “ + _disposed); 

         if (_disposed) return

         if (disposing)
         {
            ProxyHelper.CloseProxy(_instance);
         } 

         _disposed = true;
      } 

      #endregion
   }


   public static class ProxyHelper
   {
      private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 

      public static void CloseProxy(object proxy)
      {
         if (proxy == null) return
         CloseProxy(proxy as ICommunicationObject);
      } 

      /// <summary>
      /// Close the proxy in a safe manner (will not throw exception)
      /// </summary>
      /// <param name=”proxy”>The proxy to close</param>
      public static void CloseProxy(ICommunicationObject proxy)
      {
         if (proxy == null) return

         try
         {
            if (proxy.State == CommunicationState.Closing || proxy.State == CommunicationState.Closed || proxy.State == CommunicationState.Faulted)
               proxy.Abort();
            else
               proxy.Close();
         }
         catch (CommunicationException)
         {
            proxy.Abort();
         }
         catch (TimeoutException)
         {
            proxy.Abort();
         }
         catch (Exception err)
         {
            _logger.Error(err);
            proxy.Abort();
         }
         finally
         {
            proxy = null;
      }
   }
}


Hours of joy…


Almost forgot, on the next post – “How to TDD WCF code” – stay tuned…

 

Designing for testability overcomes the need for testing

In my previous post, “How to mock static class or static member for testing”, Eli replied that mocking static data can be easily achieved via TypeMock with no extra work around it. Although Eli raised a valid point while TypeMock is a very strong framework that you should check out, I still believe that designing for testability overcomes the basic need for testing your code. Trying to use some sort of powerful Profiler-based framework in order to mock your “wires” is a great thing, but I would use it only if refactoring the code will take too much time or effort that will beat the value of performing the change.


I would like to make my teammates think toward testability while designing the API.


Breaking your code so it will be easily tested will make things a little bit more complex in terms of dependency injection (object A will need to get IB in its constructor in order to work rather then creating new instance of B inside of it), but the allegedly weakness of breaking your code, making you stray from the pure OOP you’ve learned in “OOP for dummies” courses at the university, is the exact strength I see in TDD. Designing the code by writing use-cases, playing with the API, breaking classes for Single Responsibility and constant refactoring wins the purpose of testing solely or pure OO code. Don’t get me wrong, pure OO is nice on the surface, but don’t get fooled by it. You write code to create successful software, not successful practice of old paradigms.


TDD constantly demands to re-design the system and refactor it to fit the needs the system invocate, having the tests will back you up in the path. This way you can follow the guidelines of a sane development process:
1). Design the general architecture (the big picture)
2). Agree on interfaces between components
3). Unit-test user stories (use-cases) and drill down into the design by each test.
4). Build Integration tests to connect between components.

and so on…


Now, if you want to refactor existing code or add new behaviors, it’s simple:
1). Refactor the code.
2). See that everything compiles.
3). Run unit & integrations tests.
4). If all is good – check-in your source.


Claiming that TDD-OO is not pure OO is fine by me. I would prefer TDD-OO based code on pure OO any day.

 

How to set a free TDD-enabled environment



Download and install the following:

 

Testing framework:


   NUnit (version: 2.4.1 or newer)

 

Code Coverage tool:

 

   NCover (version 1.5.8 or newer)

 

Visual Studio .Net integration tool:

 

   TestDriven.Net (version 2.7.* or newer)

 



Making it play together:

 

First of all, let me apologize for the lame example, it’s kinda late for me to get creative.

Let’s create a Class Library named “Calculator.Library.Tests” and write the following test in it:


[TestFixture]
public class CalculatorTests
{
   [Test]
   public void Divide_TwoValidNumbers()
   {
      Calculator c = new Calculator();

      int expected = 3;
      int actual = c.Divide(6, 2);

      Assert.AreEqual(expected, actual);
   }
}


 

Now we’ll create another project(Class Library) named “Calculator.Library” and write the following code in it:


public class Calculator
{
   public int Divide(int a, int b)
   {
      if (b == 0)
         throw new DivideByZeroException(“err”);

      return a / b;
   }
}




Quick run of our test (print to console output):


Put the cursor in the test-method(Add_TwoValidNumbers) or in the test-class(CalculatorTests) -> right-click -> Run Test(s).


Run tests and see results in a “nice”(depends on your definition for nice) UI:

 

Right-click on the project “Calculator.Library.Tests” -> Test With -> NUnit 2.4

 

View Code Coverage:

 

Right-click on the test-method\test-class\test-project -> Test With -> Coverage. A new application named NCoverExplorer will be open – there you could explore the coverage of the code. As default, you’ll see the coverage in your tests as well which is not interesting. This can be easily fixed by changing the settings in NCoverExplorer -> View -> Options… -> Exclusions (Tab) -> pattern: “*.Tests” -> Add.

 

You can see that we have 75% coverage at the moment:

 

ncoverexplorer.JPG

 

 

We can now add the following test to check the missed path (and then simply call Test With -> Coverage again):


[Test]
[ExpectedException(typeof(DivideByZeroException))]
public void Divide_TryToDivideByZero_ThrowsException()
{
   Calculator c = new Calculator();
   c.Divide(6, 0);
}


 

Easy, Fast, Free and (almost) Fully Integrated in my development environment.
Life is pretty good.

 

How to mock static class or static member for testing

One of the problems with static members or static classes is that you can’t mock them for proper unit-testing. Instead of taking this fact for granted, let’s demonstrate it. Assume that we have the following classes (please note, this is just an example, not production code or anything that I’ll be proud of later on):


public class CsvDataExtractor
{
    private string _documentPath;

    public CsvDataExtractor(string documentPath)
    {
        _documentPath = document;
    }

    public string ExtractFullName()
    {
        string content = CsvDocumentReader.GetContent(_documentPath);
        string fullName = // extract full name logic
        return fullName;
    }
}


[Test]
public void ExtractFullName_DocumentHasFirstNameAndLastNameOnly()
{
    CsvDataExtractor extractor = new CsvDataExtractor(“c:\test.csv”);
    
    string result = extractor.ExtractFullName();
    
    Assert.AreEqual(“ellenbogen”, result);
}


 

This test is not good as we can’t test the ExtractFullName by itself – we’re testing that CsvDocumentReader.GetContent works as well. In addition, we’re depend on external file because this is what CsvDocumentReader.GetContent expects to receive.

 


Here are our options to solve this dependency so we could test ExtractFullName method by itself:

 

1). Refactor the static class into “instance” class and implement some sort of IDocumentReader interface.


Now CsvDataExtrator can get IDocumentReader in its constructor and use it in ExtractFullName. We could mock the interface and determine the result we want to get from the mocked object. Here is the refactored version:


public interface IDocumentReader
{
   string GetContent(string documentPath);
}

public class CsvDataExtractor
{
   private string _documentPath;
   private IDocumentReader _reader;

   public CsvDataExtractor(IDocumentReader reader, string documentPath)
   {
      _documentPath = document;
      _reader = reader;
   }

   public string ExtractFullName()
   {
      string content = _reader.GetContent(_documentPath);
      string fullName = // extract full name logic
      return fullName;
   }
}

[Test]
public void ExtractFullName_DocumentHasFirstNameAndLastNameOnly()
{
   DocumentReaderStub reader = new DocumentReaderStub();
   reader.ContentToReturn = “oren,ellenbogen”;

   CsvDataExtractor extractor = new CsvDataExtractor(reader, “not important document path”);

   string result = extractor.ExtractFullName();

   Assert.AreEqual(“ellenbogen”, result);
}

internal class DocumentReaderStub : IDocumentReader
{
   public string ContentToReturn;
   public string GetContent(string documentPath) { return ContentToReturn; }
}


 

Pros: (1) We can use mocking framework (Rhino Mocks for example is a great choice, and I’m not getting payed for it. I swear) to create stubs\mocks really fast and almost with no code. (2) Static classes and static members can not be easily tested, so we can save a few painful minutes\hours to the our teammates by refactoring now. (3) This one relates to reason 1 – If we need to mock several methods of our static class CsvDocumentReader, this is a better solution as we can achieve it easily with mocking framework.
Cons: (1) It’s not always possible to refactor the original static class. For example, we can’t change Microsoft’s Guid static class to control NewGuid() method, assuming that we need to mock it.

 

2). Wrap the static class with an instance class and delegate calls:


We can create an interface that expose all the functionality of the static class. Then all we need to do is wrap it with a simple class that will delegate the calls to the static class:


// the interface should look exactly like the static class we want to wrap !
public interface IDocumentReader
{
   string GetContent(string documentPath);
}

// This class will simply delegate calls to the static class
public class CsvDocumentReaderWrapper : IDocumentReader
{
    public string GetContent(string documentPath)
    {
        return CsvDocumentReader.GetContent(documentPath); // call the original static class
    }
}



The CsvDataExtractor implementation and the tests are exactly the same as option 1.

 

Pros: You can enjoy all the Pros of option 1.

Cons: (1) Wrapping is costly performance and especially in maintenance. In addition, you suffer from all of the Cons of option 1.


 

3). Use “protected virtual” method to call the static member and override it:


public class CsvDataExtractor
{
   private string _documentPath;

   public CsvDataExtractor(string documentPath)
   {
      _documentPath = document;
   }

   public string ExtractFullName()
   {
      string content = GetDocumentContent();
      string fullName = // extract full name logic
      return fullName;
   }

    protected virtual string GetDocumentContent()
    {
        return CsvDocumentReader.GetContent(_documentPath);
    }
}

[Test]
public void ExtractFullName_DocumentHasFirstNameAndLastNameOnly()
{
   TestableCsvDataExtractor extractor = new TestableCsvDataExtractor(“not important document path”);
   extractor.ContentToReturn = “oren,ellenbogen”;

   string result = extractor.ExtractFullName();

   Assert.AreEqual(“ellenbogen”, result);
}

public class TestableCsvDataExtractor : CsvDataExtractor
{
    public string ContentToReturn;
    
    public TestableCsvDataExtractor(string documentPath) : base(documentPath)
    {
    }
    
    protected virtual string GetDocumentContent()
    {
        return ContentToReturn;
    }
}


Pros: (1) if we can’t refactor the original static class – it’s a very fast & simple  solution to use (.vs. wrapping it).

Cons: (1) Not a perfect solution from an “elegant code” prospective.

 

 

 

I love to use option 3 if refactoring is too hard to (or not possible to) achieve but no doubt, option 1 will give you the best results if you’re looking a few steps ahead.

 

Writing Thread Safety tests for instance data

In my last post, I wrote about Implementing a simple multi-threaded TasksQueue. This post will concentrate in how to test for Thread Safety of the queue. Reminder: our queue is used by multiple consumers which means that I must make sure that before each Enqueue\Dequeue\Count, a lock will be obtained on the queue. Imagine that I have 1 item in the queue and 2 consumers trying to dequeue this item at the same time from different threads: The first dequeue will work just fine but the second will throw an exception (dequeue from an empty queue). We’re actually trying to make sure that this queue works as expected in multi-threaded environment. So far about our goal.

So how can we test it?
Testing for the queue’s thread safety through testing of TasksQueue, the way it’s written now, can be quite hard and misleading. The ConsumeTask method calls dequeue inside a lock but what if we had a thread-safety-related-bug there? do we test only that the dequeue works as expected? not really. ConsumeTask (1) dequeue an item and then (2) “consume it”. We’re actually testing 2 behaviors\logics – this way, it’s really hard to test only for the queue’s thread safety. We should always test a single method for a specific behavior and eliminate dependencies. Only when we cover our basis, we can check for integration between multiple components (the underlying queue and the TasksQueue).


One way of allegedly achieving this goal is to create a decorator around the queue, let’s call it SafeQueue, which will encapsulate a queue and wrap it with thread-safe forwarding of the calls (it will lock some inner object and call the original queue). The SafeQueue could be tested then by its own and used by our TasksQueue. This will “enable” us to remove the locking in the TasksQueue and use Set\WaitOne instead of Pulse\Wait in order to notify our consumers on arrival of a new task: 


while (_safeQueue.Count == 0)
   Monitor.WaitOne();

// NOTICE: by the time we get here, someone could have pulled the last item from the queue on another thread!
string
item = _safeQueue.Dequeue();


WATCH OUT: This is a deadly solution that will make our TasksQueue break in a multi-threaded environment. Just like that, our code is not thread-safe anymore although we’re using a SafeQueue that expose (atomic) thread-safe methods\properties. This is exactly why instance state should not be thread-safe by default (more details at Joe Duffy’s post).


The locking of the queue should remain in our TasksQueue, but we should separate the dequeue part from the handling part and check each one by its own. We’ll check the dequeue part for thread-safety(assuming that the underlying queue was tested by itself) and the handling part for pure logic. We can now test that for X calls for enqueue we get the same X calls for dequeue.


Here is the refactored code:


private void ConsumeTask()
{
   while (true)
   {
      string task = WaitForTask();

      if (task == null) return; // This signals our exit

      try
      {
         // work on the task
      }
      catch (Exception err)
      {
        // log err & eat the exception, we still want to resume consuming other tasks.
      }
   }
}


protected virtual string WaitForTask()
{
   lock (_locker)
   {
      // if no tasks available, wait up till we’ll get something.
      while (_queue.Count == 0)
         Monitor.Wait(_locker);

      // try to put it outside of the lock statement and run the test(bellow)
      return
_queue.Dequeue(); 
   }
}


public virtual void EnqueueTask(string task)
{
   lock (_locker)
   {
      _queue.Enqueue(task);
      Monitor.Pulse(_locker);
   }
}


Now we can create a simple test for the thread safety by overriding both of the enqueue\dequeue methods:


internal class TestableTasksQueue : TasksQueue
{
   private static int _dequeueCount = 0;
   private static int _enqueueCount = 0;

   public TestableTasksQueue(int workerCount) : base(workerCount) {}

   protected override string WaitForTask()
   {
      string item = base.WaitForTask();
      Interlocked.Increment(ref _dequeueCount);
      return item;
   }

   public override void EnqueueTask(string task)
   {
      base.EnqueueTask(task);
      Interlocked.Increment(ref _enqueueCount);
   }

   public static int DequeueCount
   {
      get { return _dequeueCount; }
   }

   public static int EnqueueCount
   {
      get { return _enqueueCount; }
   }
}


The tricky part here is the test itself. Because of subtle multi-threading issues, we can’t actually know when 2 (or more) threads will try to dequeue on the same time, so we have to run this test enough times in order to detect bugs. Here is a little sample:


[TestFixture]
public class TasksQueueTests
{
   [Test]
   public void Counting_DequeueAndEnqueueCountsShouldBeEqual()
   {
      for (int j = 0; j < 1000; j++)
      {
         using (TestableTasksQueue queue = new TestableTasksQueue(5))
         {
            for (int i = 0; i < 100; i++)
               queue.EnqueueTask(“test” + i);
         }

         Assert.AreEqual(TestableTasksQueue.DequeueCount, TestableTasksQueue.EnqueueCount);
      }
   }
}


Well, it’s not that elegant, I know, but thread-safety is hard to test.
I would love to hear some suggestion from you regarding this issue.

 

ClientSideExtender, version 0.0.0.1

Damn, it was so much fun to play a little with TDD and abstract the lousy API given by Microsoft to register client-side script. I’ll write about the process and design changes I’ve made due to testability reasons. TDD is a great design tool, it’s amazing to witness the “before” and “after” of your code, all because of the requirements to test things separately.


Here are a few API samples, taken from the Demo project (you can play with it and see the results):


public partial class _Default : Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      ClientSideExtender script = ClientSideExtender.Create(this);

      script.RegisterMethodCall(“alert”).WithParameters(“hello world!”).ToExecuteAt(Target.EndOfPage);

      script.RegisterVariable<string>(“myStringVar”).SetValue(“test”).ToExecuteAt(Target.EndOfPage);
      script.RegisterVariable<int>(“myIntegerVar”).SetValue(5); // Target.BeginningOfPage as default

      script.RegisterScriptBlock(“alert(‘proof of concept – state:’ + document.readyState);”).ToExecuteAt(Target.PageLoaded);
   }
}


Keep in mind that I’m only supplying a different API (abstraction) of Microsoft’s implementation. In order to accomplish that, I’m using Windsor to wire the ClientSideExtender with the new ajaxian ScriptManager(supports UpdatePanel), which will actually be responsible to register the script under the hood. You can look at the web.config (under the <castle> element) for more details.


Source:
Lnbogen.Web.UI.zip (253.56 KB)

 

Using Rhino Mocks to Unit Test Events on Interfaces, take 2

Phil Haack gives an excellent example of how to test a registration to event while implementing MVP pattern (via Rhino Mocks). If you did not read it yet, take a pause for 2 minutes and give it a look; It is worth it, I promise.


The only thing that bothers me in the example is that the need to assert the triggering of the event kind of spoiled the code. I think that in those scenarios, it’s much better to use some sort of Stub and override the class under test in order to keep the it cleaner. So instead of having this code:


public class Presenter
{
   IView view;
   public Presenter(IView view)
   {
      this.view = view;
      this.view.Load += new EventHandler(view_Load);
   }

   public bool EventLoaded
   {
      get { return this.eventLoaded; }
      set { this.eventLoaded = value; }
   }

   bool eventLoaded;

   void view_Load(object sender, EventArgs e)
   {
      this.eventLoaded = true;
   }
}



I would have created something like this:


public class Presenter
{
   IView view;
   public Presenter(IView view)
   {
      this.view = view;
      this.view.Load += new EventHandler(view_Load);
   }

   protected virtual void view_Load(object sender, EventArgs e)
   {
       // production code here
   }
}


// This will go in the PresenterTests class
public class TestablePresenter : Presenter
{
   public bool WasEventLoaded = false;
   protected override void view_Load(object sender, EventArgs e)
   {
       WasEventLoaded = true;
   }
}



Now we can create an instance of TestablePresenter and Assert the WasEventLoaded field.
My guess is that Phil actually did something like this in his project and merely wanted to show an example, but I still thought it was important enough to demonstrate this separation as I firmly believe we must make sure that our need for tests will not actually hurt the design.

 

TDD in the eyes of a simpleminded: Manual Stub .vs. Mock Stub

Source Code:


RhinoMocksExample.zip (94.18 KB)


You will need to download and install Nunit 2.2.8 and RhinoMocks(for .Net 2.0) in order to run the tests.


Background:


Not as usual, we’ll start with the code and continue with it’s UnitTests.
We have a single, simple class named MailService. This class contains one method named MailText(string textToMail, params MailInfo[] mailList) that looks like this:


public class MailService
{
   private IMailValidator m_mailValidator;
   public IMailValidator MailValidator // setter, getter

   public void MailText(string textToMail, params MailInfo[] mailList)
   {
      foreach (MailInfo mail in mailList) { //I know I can collect addresses…
         ValidationResult validationResult = this.MailValidator.Validate(mail);

         if (!validationResult.IsValid)
            throw new ArgumentException(“Invalid mail: “ + validationResult.ValidationMessage, “mail”);

         // Send the email somehow…
      }
   }
}


And here is the IMailValidator, MailInfo and ValidationResult:


public class MailInfo {
   public string Address; //not best practice
   public MailInfo(string address) { this.Address = address; }
}

public class ValidationResult {
   public bool IsValid; //not best practice
   public string ValidationMessage; //not best practice

   public ValidationResult() { IsValid = true; ValidationMessage = string.Empty; }

   public ValidationResult(bool isValid, string message) {
      IsValid = isValid;
      ValidationMessage = message;
   }
}

public interface IMailValidator {
   ValidationResult Validate(MailInfo mail);
}


That is pretty straightforward I hope.


Testing inner behavior:


MailService.MailText has one dependency to IMailValidator. One way of testing our MailService.MailText method is via manual stub implementation of IMailValidator. Let’s examine the tests and then look at the manual stub I’ve created.


1). Manual stub based testing:

[TestFixture]
public class MailServiceTests
{
   [Test]
   public void MailText_OneValidEmail_MethodWorks()
   {
      MailService service = new MailService();
      MailInfo mail1 = new MailInfo(“valid@mercury.com”);

      service.MailValidator = new StubMailValidator();

      service.MailText(“Enlarge your ‘memory stick'”, mail1);
   }

   [Test]
   [ExpectedException(typeof(ArgumentException))]
   public void MailText_OneValidEmailAndOneInvalidEmail_ThrowException()
   {
      MailService service = new MailService();
      MailInfo validMail = new MailInfo(“valid@mercury.com”);
      MailInfo invalidMail = new MailInfo(“invalid.com”);

      service.MailValidator = new StubMailValidator();

      service.MailText(“Enlarge your ‘memory stick'”, validMail, invalidMail);
   }
}


And here is the simple StubMailValidator in one of it’s versions: (This stub was developed after the first test(MailText_OneValidEmail_MethodWorks) was written)


public class StubMailValidator : IMailValidator
{
   public ValidationResult Validate(MailInfo mail)
   {
      ValidationResult res = new ValidationResult(); //default: valid.
      if (mail.Address.IndexOf(“.com”) == -1) {
         res.IsValid = false;
         res.ValidationMessage = “The email address must end with .com”;
      }

      return res;
   }
}


NOTICE: Manual stubs with inner logic can be devastating !


As you may or may not notice, this stub has a bug in it. Just look at the second test on the “invalid.com” MailInfo. This is an invalid email address and yet, our stub will say that it’s valid and fail our second test. This is extremely dangerous! It is one of the things that makes people afraid from Unit Testing. When your stub need to switch his response according to a given parameter(s) based on some logic, you better switch your manual stub with dynamic\generated stub. You don’t want any test-related logic outside of your test method. Let’s look at mocked stub testing.


2). Mock stub based testing:


I’m using Oren Eini’s (aka Ayende) RhinoMocks for simulating “controlled” implementation of IMailValidator. That means that you are creating some dynamic implementation of IMailValidtor and you are telling it how to act when the tested method calls it.


Let’s look at our first test:


[Test]
public void MailText_OneValidEmail_MethodWorks()
{
   MailInfo validMail = new MailInfo(“valid@mercury.com”);
   ValidationResult validValidationResult = ValidationResult(true, string.Empty);

   // —— (1) ——-
   MockRepository mocks = new MockRepository();
   IMailValidator validator = (IMailValidator)mocks.CreateMock<IMailValidator>();
   Expect.Call(validator.Validate(validMail)).Return(validValidationResult);
   // ——————

   service.MailValidator = validator;

   mocks.ReplayAll(); // Make sure the mock object is ready to “respond”

   service.MailText(“Enlarge your ‘memory stick'”, validMail);

   mocks.VerifyAll(); // Make sure everything was called correctly.
}


(1) – This is the important stuff. I’m asking the MockRepository to create a new Mock from IMailValidtor type that our MailService expect. The line in bold tells this story: “listen dear mocked validator, if someone calls your Validate method with the parameter validMail – please send him back validValidationResult object”. If we know that our validator will be called twice – we’ll have two lines with Expect.Call as needed.


One of our main purpose in UnitTesting is to test one method (and one method only) and see if it behaves correctly if it receive a certain data. We also want to check the stomach of the method, what happen if our tested method calls another method(dependency) that return “1” – will it still behave as expected? Via Mock object I can control the dependency object’s result easily inside the test. This make it very easy to detect bugs in contrast to our manual stub that sits somewhere else, outside of our test.


Recap:


If you have a dependency to some other object and your manual stub start to contain logic, you should mock that dependency and control the returned values in the same place you write your tests via mock object.


Bonus (delegates style Interaction Based Testing):


[Test]
public void MailText_OneValidEmail_MethodWorks2()
{
   MailInfo validMail = new MailInfo(“valid@mercury.com”);
   ValidationResult validValidationResult = ValidationResult(true, string.Empty);

   RunMock<IMailValidator>(
      delegate(IMailValidator validator, MockRepository repository) {
         Expect.Call(validator.Validate(validMail)).Return(validValidationResult);

         service.MailValidator = validator;
         repository.ReplayAll();

         service.MailText(“Enlarge your ‘memory stick'”, validMail);
      }
   );
}

private void RunMock<TObjectToMock>(MockedProc<TObjectToMock> func)
{
   MockRepository mocks = new MockRepository();
   TObjectToMock obj = (TObjectToMock)mocks.CreateMock<TObjectToMock>();

   func(obj, mocks);

   mocks.VerifyAll();
}

private delegate void MockedProc<TObjectToMock>(TObjectToMock mockedObject, MockRepository repository);


Enjoy!

 

TDD Workshop: SeeCompass v0.2 is available

This (very)little beauty is getting along quite nicely. I’m going to work quite a bit on it in the following days so keep tracking…


source:


Lnbogen.SeeCompass_v0.2.zip (205.34 KB)

 

TDD Workshop: SeeCompass v0.1 is available

After sitting with Roy during our last meeting, we managed to write some neat tests and code and the SEE(Simple Expression Engine) infrastructure started to crystallized. Roy even managed to refactor the name of my infrastructure and brought a brilliant suffix – SeeCompass. SEE is like a compass that helps you navigate in the ocean of data; man, I think that the web-bully will not be happy with this phrase.


If you don’t remember what is SeeCompass all about read this post.


Source:


Lnbogen.SeeCompass.zip (156.39 KB)


How to start:


1. Open the solution (I know, revolutionary).
2. Open Lnbogen.SeeCompass.Framework.Tests project.
3. Open the file FilterExpressionTests.cs under FilterExpression directory.
4. Jump to the test Build_EmptyFilter_EmptyString (remember the method name structure: MethodToTest_MethodState_ExpectedResult).
5. Move on to the next test, one at a time.



I know, it can be a little hard to grasp the “entire picture” at the moment, but the tests should give you a good pick at the future.
As always, I left one failing test which will lead to a very drastic refactoring (BetweenExpression should have more than one parameter) – this will give me an entry point to continue.