03 October 2007

Unit testes and events

While my last project I met a problem with applying unit testes to asynchronous methods. My program had to load a big amount of data from database. The simple method DownloadData took too much time so I had decided to build and invoke asynchronous method like BeginDownloading. As the data was downloaded the OnDownloaded event was raised. The class had look similarly to this one below.

public class DatabaseFacade

{

public event EventHandler OnDownloaded;

public DatabaseFacade() { }

public virtual void BeginDownloading()

{

Console.WriteLine("Begin downloading");

System.Threading.Thread.Sleep(2000);

this.RaiseOnDownloaded();

}

protected virtual void RaiseOnDownloaded()

{

if (this.OnDownloaded != null)

this.OnDownloaded(this, new EventArgs());

}

}



Now it is the main problem how to test the type of DatabaseFacade with unit tests. It is not really easy because of the sequence invoking each test method. To solve this problem we have to apply the ManualResetEvent. The base task of this class is block the executing the method till the me object call Set which means that all waiting threads can proceed. If the method Set will not called in i.e. 5 seconds then the testing method will stop waiting for the call from ManualResetEvent and carry on executing. Below I attache an example:

[Test]

public void BeginDownloadingTest()

{

ManualResetEvent me = new ManualResetEvent(false);

bool raised = false;

DatabaseFacade df = new DatabaseFacade();

df.OnDownloaded += new EventHandler(delegate(object sender, EventArgs e)

{

raised = true;

Console.WriteLine("Done");

me.Set();

});

df.BeginDownloading();

me.WaitOne(5000, false);

Assert.IsTrue(raised);

}

Labels: , ,

1 Comments:

At 10/11/08 21:24, Anonymous Anonymous said...

Well said.

 

Post a Comment

<< Home