Unit testing Facade pattern

Published 31.10.2009 01:02 PM by Admin in IOC | Patterns | Testing | Unit testing

The facade pattern is commonly used software engineering design pattern. His purpose is to provide simplified interface to a larger body of code.

It has several good uses:

- Make a software library easier to use and understand, since the facade has convenient methods for common tasks.
- Make code that uses the library more readable, for the same reason.
- Reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system.
- Wrap a poorly-designed collection of APIs with a single well-designed API (as per task needs).

Importance of this Design pattern we cannot underestimate.

In unit testing one of good practice is to put our dependencies in constructor of class. Facade pattern class however cannot have dependencies in constructor because it increase complexity of code.

In this blog post I will show you how to unit test facade pattern.

If I have 2 classes : EmailLogger and DatabaseLogger  and these two classes have same porpoise to Log same data.

These two classes have dependencies on another classes.

I want to have one class that I will call Logger with one method called Log that will be Facade for these two classes.

Class EmailLogger looks like this :

public class EmailLogger:ILogger
{
private readonly IEmailProxy _emailProxy;
public EmailLogger(IEmailProxy emailProxy)
{
_emailProxy = emailProxy;
}
public void Log(string message)
{
if(_emailProxy!=null)
{
_emailProxy.SendEmail(message);
}
else
{
throw new ArgumentNullException("_emailProxy");
}
}
}

 

This class have dependency on another class called EmailProxy and accepts interface IEmailProxy in constructor.

Class DatabaseLogger looks similar to EmailLogger :

 

public class DatabaseLogger:ILogger
{
private readonly IDatabaseMechanism _databaseMechanism;
public DatabaseLogger(IDatabaseMechanism databaseMechanism)
{
_databaseMechanism = databaseMechanism;
}
public void Log(string message)
{
if(_databaseMechanism!=null)
{
_databaseMechanism.SendLogToDatabase(message);
}
else
{
throw new ArgumentNullException("_databaseMechanism");
}
}
}

 

This class have dependency on class called DatabaseMechanism and accepts another interface IDatabaseMechanism in constructor.

And finally we have class called Logger that will be Facade for these two classes .

In this example I will use singleton implementation Unity container and Rhino Mocks.

 

public class Logger:ILogger
{
private readonly ILogger _emailLogger;
private readonly ILogger _databaseLogger;
public Logger()
{
IContainer container = new UnityContainer();
_emailLogger = container.Resolve("EmailLogger");
_databaseLogger = container.Resolve("DatabaseLogger");
}
public void Log(string message)
{
if(_emailLogger!=null)
{
_emailLogger.Log(message);
}
else
{
throw new ArgumentNullException("_emailLogger");
}
if (_databaseLogger != null)
{
_databaseLogger.Log(message);
}
else
{
throw new ArgumentNullException("_databaseLogger");
}
}
}

 

And of course we need to have some registration in container in some BootStraper class :

 

public static class BootStraper
{
public static void SetUp()
{
IContainer container = UnityContainer.Instance();
container.RegisterType();
container.RegisterType();
container.RegisterType("EmailLogger");
container.RegisterType("DatabaseLogger");
}
}

 

Consuming this class is simple :

 

public class Consume
{
public void ConsumeLogger()
{
Bootstraper.SetUp();
ILogger logger=new Logger();
logger.Log("Some message");
}
}

 

Code is simple and understandable and we don’t need to use any container to call this class . If someone reference your dll it can use your code without any container registration or resolve . You just call  method in that class and he not see container calls and deeper logic inside this Facade class.

And finally test is very simple too :

 

[TestClass]
public class LoggerTests
{
private readonly ILogger _emailLogger;
private readonly ILogger _databaseLogger;
private readonly IContainer _container;
public LoggerTests()
{
_container = UnityContainer.Instance();
_emailLogger = MockRepository.GenerateMock();
_databaseLogger = MockRepository.GenerateMock();
_container.RegisterInstance("EmailLogger", _emailLogger);
_container.RegisterInstance("DatabaseLogger", _databaseLogger);
}
[TestMethod]
public void Log_AcceptCorrectArgs_CallsEmailLoggerLog()
{
//arrange
ILogger logger = new Logger();
//act
logger.Log("Something");
ILogger emailLogger = _container.Resolve("EmailLogger");
//assert
emailLogger.AssertWasCalled(x => x.Log("Something"));
}
}

 

We register instance of mock objects EmailLogger and DataBaseLogger in Container and resolve later in test to ensure that correct method of mock object is called.

I hope this will help you in some of your projects.

Currently rated 2.7 by 3 people

  • Currently 2.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

VSTestHost hang on Windows 7 RTM

Published 06.09.2009 06:08 PM by Admin in Testing
Tags: ,

I have Windows 7 RTM installed and Visual Studio 2008 with SP1. After writing some simple unit test and run it I have got VSTestHost.exe not responding error.

First I have thought that is Windows 7 error. I have looked and find some hotfix and if you have some similar problems I suggest to try run sample test with no code to ensure that problem is not in your code. That hotfix is on this address : http://code.msdn.microsoft.com/970449/Release/ProjectReleases.aspx?ReleaseId=2830

After better looking in my code I have found that problem is in my own code. I have had recursive call to a method inside unit test so test method is never finishing and VSTestHost is hang out after few seconds with unknown error.

Hopefully this post will help someone struggling with similar issues…

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Unit testing private methods yes or no?

Published 12.04.2009 05:01 PM by Admin in Testing
Tags:

I am beginner at field TDD. Recently I have conversation with Dror Helper  should I test my private methods or not. After I have talked with him and little reconsider I thing we don’t need to test private methods.

If we need to test private methods we can do this trough public methods that call those private methods.

For example if we have one public method that calls one or several other private methods like this:

public static bool LogIn(string userName, string password)

        {

            var user = new User(userName, password);

 

            if (verifyThatUserIsValid(user))

            {

 

                return true;

            }

            else

            {

                return false;

            }

        }

 

 

 

        private static bool verifyThatUserIsValid(User user)

        {

            throw new NotImplementedException();

        }

 

So if I want to make unit tests for method verifyThatUserIsValid I can easily make unit tests for method LogIn to test that method. What do you think about this?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

SqlException class does'nt have public constructor

Published 08.03.2009 07:43 AM by Admin in C# | Sql | Testing
Tags: , ,

I am currently preparing ado.net 3.5 course so I try to throw SqlException in one of my examples and realize that SqlException class is sealed and has no public constructor.

I have found solution on Rido blog http://blogs.msdn.com/rido how to create SqlException using reflection.

        public static SqlException CreateSqlException(string errorMessage, int errorNumber)

        {

 

            SqlErrorCollection collection = GetErrorCollection();

            SqlError error = GetError(errorNumber, errorMessage);

            MethodInfo addMethod = collection.GetType().

            GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);

            addMethod.Invoke(collection, new object[] { error });

            Type[] types = new Type[] { typeof(string), typeof(SqlErrorCollection) };

            object[] parameters = new object[] { errorMessage, collection };

            ConstructorInfo constructor = typeof(SqlException).

            GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);

            SqlException exception = (SqlException)constructor.Invoke(parameters);

            return exception;

        }

        private static SqlError GetError(int errorCode, string message)

        {

            object[] parameters = new object[] {

            errorCode, (byte)0, (byte)10, "server", message, "procedure", 0 };

            Type[] types = new Type[] {

            typeof(int), typeof(byte), typeof(byte), typeof(string), typeof(string),

            typeof(string), typeof(int) };

            ConstructorInfo constructor = typeof(SqlError).

             GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);

            SqlError error = (SqlError)constructor.Invoke(parameters);

            return error;

        }

 

        private static SqlErrorCollection GetErrorCollection()

        {

            ConstructorInfo constructor = typeof(SqlErrorCollection).

            GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);

            SqlErrorCollection collection = (SqlErrorCollection)constructor.Invoke(new object[] { });

            return collection;

        }

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Radenko Zec Blog

Silverlight, C#, WCF, WPF,NET...