NAVmoble - the pocket-sized ERP
Optimized for Microsoft Dynamics NAV and Windows Mobile powered devices

Thursday, April 07, 2005

Service Locator Unit Test

Required reading Service Locator pattern and .NET post.

What about writing unit tests for our Service Locator?
Actually they may look quite straight forward. It is even esier, because we dont have to deal with a complicated service instantiation code.

Having the sample implementation from the prev. post, we may write the following code in order to test our consumer class. Actually some changes are needed in order to use the code in unit testing. Sample code may be obtained from here

[TestFixture]
public class ServiceConsumerTest
{
ServiceConsumer consumer;
[SetUp]
public void SetUp()
{
consumer = new ServiceConsumer();
}
[TearDown]
public void TearDown()
{
consumer=null;
}


[Test]
[ExpectedException(typeof(ApplicationException))]
//we expect our consumer to raise exception if not in container
public void NotContainedConsumer()
{
consumer.Process();
}

[Test]
public void ContainedConsumer()
{
//embed the consumer into our container
ConfigurableContainer container = new ConfigurableContainer();
container.Add(consumer);

//prepare App configuration - we may test our container with various services
imlpementations and even mocked services

//call processing

consumer.Process();

//check expected result....and assert
}
}

In order to have this test working with VS2003, we need to add the following line in
menu Project/Properties/Build Events/Post Build Event Command Line

copy "$(ProjectDir)App.config" "$(TargetPath).config"


This will force VS2003 to copy our configuration file into the output directory, thus making it available for NUnit and our tests.

Of course, we may mangle the configuration file in our test in order to perform tests with other service implementations and even mocked services.
Better aproach could be to provide API for container configuration.

No comments: