JAJAH Development Blog

Blogs by JAJAH Developers

Archive for the ‘unit testing’ Category

How to: Unit test events

Tuesday, January 22nd, 2008

When we come to write unit tests we stumble upon many different problems with many different parts of our code, because no matter how hard you try, your code is never as simple as the examples around the web. If it’s singletons, static methods, private members that need mocking, or even events that need to be checked.

lately I spent some time writing unit tests and fumbled around with many of this problems. There are many articles around the web telling you the problem is not that you don’t know how to test this parts, it is that it shouldn’t exist in the first place. I really don’t like this answer, saying I shouldn’t write my code this way because there is a better one is a valid argument, but telling me I HAVE to change my code in order for it to work is usually not true. Some places don’t say this but still, most don’t give you a solution.

After this brief intro I will go into saying that I will try in a few different posts to clear up some of the problems in unit testing, mainly the ways to overcome them.

Lets start =]

As the title states, in this post I will show how to unit test events.

What we are going to do here is use an Anonymous delegate in order to catch the event inside our test.

The code: (look afterwards for the explanation and break down)

[TestFixture]
public class SettingsFixture
{
    [Test]
    public void ChangeSettingFiresSettingsChangedEvent()
    {
        // success variable
        bool success = false;

        // new setting
        string key = "SomeKey";
        string value = "SomeValue";

        // set a new instance
        SettingsManager settingsManager = new SettingsManager();

        // register to the event
        settingsManager.SettingsChanged += delegate(object sender,
          EventArgs e)
        {
            // event raise, test successfull
            success = true;
        };

        // update a setting to raise the event
        settingsManager.UpdateSetting(key,value);

        Assert.True(success);
    }
}

So what we have here?

We have a TestFixture with a single Test called:

ChangeSettingFiresSettingsChangedEvent

Change Setting Fires SettingsChanged Event.

First, we setup the success variable which we will commit later as the test’s result.

Second, set up our "new" setting, if we would use a special Type to submit to the UpdateSetting method, ISetting lets say, this will be the place to Mock(Mocking will be discussed in a future post, I will link to it then) it.

Third, setup a new instance of our SettingsManager.

Fourth, register to the SettingsChanged event as we usually will, with one big difference. instead of using a new instance of the right delegate we use an Anonymous delegate, look at the code for the syntax, it is very simple.

Fifth, call UpdateSetting with our "new" setting so the event will be raised.

Sixth, commit the result, hoping that it all went as planned ;].

Seventh, show off to your friends and go home, it’s late! (somewhere in the world…)

Hope it was clear enough.

A nice post about this:

Just to clarify: I am using C#(if you haven’t noticed yet) with NUnit.

See you next time =].

Nadav

Sunday, November 25th, 2007

The is a part of the Castle project but can be used as a standalone assembly.

The dictionary adapter lets you wrap a dictionary with an interface definition and access that dictionary through the interface. This gives the advantage of typed data access on top of a dictionary and don’t forget the intellisense in the IDE.

The example I will use shows the use of a dictionary adapter in order to enable access to configuration data.  It contains a class:

/// 
/// This class uses configuration.
/// Instead of accessing the configuration directly,
/// it receives it in the constructor.
/// 
public class DataBaseAccess
{
    private IDataBaseAccessConfig m_config;

    /// The configuration that
    /// this class uses to access the database.
    /// 
    public DataBaseAccess(IDataBaseAccessConfig config)
    {
        m_config = config;
    }

    public void ConnectToDataBase()
    {
        Console.WriteLine("Server Ip: {0}", m_config.ServerIp);
        Console.WriteLine("DataBase: {0}", m_config.DataBaseName);
        Console.WriteLine("User: {0}", m_config.UserName);
        Console.WriteLine("Password: {0}", m_config.Password);
        Console.ReadLine();
    }
}

As you can see, this class expects a config object that implements the the IDataBaseAccessConfig interface. This interface is defined as:

/// 
/// Defines the data for data base access.
/// 
public interface IDataBaseAccessConfig
{
    string ServerIp { get;}
    string DataBaseName { get;}
    string UserName { get;}
    string Password { get;}
}

In the example, the database access data is defined in the appSettings section of the application configuration file. In order to pass it to the DataBaseAccess class, it is being wrapped like this:

// In real world example the factory should be cached.
// Create the adapter on top of the configuration dictionary.
IDataBaseAccessConfig configAdapter =
    new DictionaryAdapterFactory().
        GetAdapter(configData);

where the configAdapter is passed.

Now what happened here? The DictionaryAdapterFactory emit code in runtime that implements a wrapper class that implemets the IDataBaseAccessConfig interface and this class, when a property is being read, gets the value for the dictionary that is wrapped, in this case, the configData dictionary.

What is it good for?

1) In my opinion, it is nicer to access an interface rather than passing a configuration dictionary to the class which involves querying the data by using string literals.

2) When passing the data through the constructor instead of accessing the ConfigurationManager directly in the code we make our code better by preventing access to singletons, therefore making the code testable and agnostic to the real implementation, may it be the application configuration file, configuration defined in the database or any other implementation.

3) Intellisense…

The example solution is here

Jajah is the VoIP player that brought you web-activated telephony.