«
February 2009
»
Unit Testing Custom Config Section
I recently had to write some unit tests to test a custom configuration section. I was using NUnit so I didn't want to use the config file that would be loaded by NUnit, for example nunit-gui.exe.config, but instead wanted to load one or more separate test config files. The solution was to use the ExeConfigurationFileMap class. For example, say I have this config file:
<configuration>
<configSections>
<section name="MySettings" type="MySettings, TestConfigSection" />
</configSections>
<MySettings
testSetting="test" />
</configuration>
I can retrieve values from the custom section using code like this:
using System.Configuration;
public class MySettings : ConfigurationSection
{
[ConfigurationProperty("testSetting")]
public string TestSetting
{
get { return (string)this["testSetting"]; }
set { this["testSetting"] = value; }
}
}
class Program
{
static void Main(string[] args)
{
MySettings settings
= (MySettings)ConfigurationManager.GetSection("MySettings");
string testSetting = settings.TestSetting;
}
}
To unit test the MySettings class I can use an instance of ExeConfigurationFileMap to load a test config file (in this case from the current directory where the test is being run):
using System.Configuration;
using NUnit.Framework;
[TestFixture]
public class ConfigTests
{
[Test]
public void testSetting()
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "ConfigTests.config";
Configuration config
= ConfigurationManager.OpenMappedExeConfiguration(fileMap,
ConfigurationUserLevel.None);
MySettings section
= config.GetSection("MySettings") as MySettings;
Assert.AreEqual("test", section.TestSetting);
}
}
Spike
When I was at the last DeveloperDeveloperDeveloper day I came across usage of the word "spike" in software development for the first time. Extreme Programming has this definition:
Create spike solutions to figure out answers to tough technical or design problems. A spike solution is a very simple program to explore potential solutions. Build a system which only addresses the problem under examination and ignore all other concerns. Most spikes are not good enough to keep, so expect to throw it away. The goal is reducing the risk of a technical problem or increase the reliability of a user story's estimate.
When a technical difficulty threatens to hold up the system's development put a pair of developers on the problem for a week or two and reduce the potential risk.
I've noticed that when a developer has a technical problem they often try to solve it in-situ to the application they are working on. I prefer to write some completely standalone code to experiment with the problem so that I am not distracted by anything else relating to the application, such as building it or testing it. So I suppose I have intuitively been doing "spikes" for a long time.
Using spikes allowed you to isolate what you are experimenting with from your application code. This makes it much easier to share the problem with someone else. For example, a friend IM's you about a problem but you cannot check or run what she is doing because of she is not allowed you to send the application code, and even if she could you would have to install the app to run her code, whereas sending a small standalone project containing spike code presents no problems.
Another advantage of using spikes is that it separates test code from production code and makes it less likely that code of prototype quality is likely to end up on the trunk. Jeremy Miller's Don't Check In Spike Code… expands on this:
Don't Check in Spike Code…
...into the trunk.
Just like the title says, do NOT check "spike" code into the source control trunk. When you do an exploratory spike, you're generally throwing good coding practices completely out the window. You're on a focused mission to "figure out how this gosh durned thing is supposed to work." The code that you write in a spike probably sucks anyway.
Do spike whenever you're unsure how to work with some new library or technology or to try out a new object structure — but put that code in a branch. As soon as the spike has achieved its purpose, put that code aside, and write all new code in the trunk using TDD and your normal coding standards. You know, the coding and design standards that you've adopted as a team because you think those standards lead to sustainable quality. But Jeremy, I could just retrofit some unit tests around the spike code and call it good! Maybe, but you better ask yourself, am I really going to put decent tests around this code? Retrofitting unit tests never results in the same quality of tests as real test first development. Besides, as I said earlier, spike code generally sucks anyway;-)
I keep a large number of test projects containing my spikes as a reference for the various techniques, framework classes, and APIs I have experimented with. K Scott Allen responded to Jeremy's post with Spike Code and Source Control, where he describes the value of storing spike code:
Here are the kinds of things I've checked into "experiments/sallen" over the years:
- Code to isolate and reproduce compiler, framework, and library bugs.
- Code written to learn a new technology, platform, or library.
- Code that I almost threw away because I was sure it would only be needed once (like a one time data import).
- UI mockups
- Code written to evaluate a product.
- Code that doesn't work (because you'll have proof 6 months later when someone else has the same idea).
I've found that keeping a dedicated area for these types of check-ins offers some advantages:
It keeps spike code out of production branches (as Jeremy suggests). It keeps code around that you might find useful to refer to one year from now. After someone leaves a project, their experiments live on. It saves you from saying "I think I tried something like that last year but threw the code away".
David Lambert describes how a spike can turn into what he calls a "reference architecture":
In other words, once you've used the spike to prove that something can work, you want to use it to show others how it's done. When that happens, you're starting to turn your spike into a reference architecture, and this is a much more important beast than your normal spike. Here are some signs that your spike might really be turning into a reference architecture:
- It's documented. If you start to go through the trouble of explaining how this thing works, it's more than just a spike.
- It's got more than one revision. If you check in updates to your spike to illustrate new ideas instead of building a new spike, you're growing a reference architecture.
- It mimics the structure of your "real" application. If you go to the trouble of making your spike's project structure look substantially like your application's structure (or vice versa), there's a good chance you're going to end up with a reference architecture by the time you're done.
Code samples like this, particularly with some documentation, can be useful in explaining how to do something, often more so than a design document.
So, "spike" is a pretty obvious concept but with a little thought you can get a lot more value from it.
Fowler on Dependency Injection vs Service Locator
Following my last post on Dependency Injection Andy McMullan posted a comment to my Twitter feed:
Just read Fowler's IOC/DI page - seems he disagrees with Prasanna about the superiority of DI over Serv Locator.
In the article Inversion of Control Containers and the Dependency Injection pattern Fowler compares Service Locators and DI and presents some arguments for and against DI compared with Service Locators:
For DI:
- Easier to determine what dependencies a component has - look at constructor.
- Component does not have dependency on Service Locator so there is not a problem if the component is used with a different framework.
- DI may make testing easier but a good Service Locator mechanism will make stubbing equally feasible
Against DI:
- Harder to debug and understand.
- Component cannot request extra services from injector once it had been configured.
In Concluding Thoughts Fowler says:
… Dependency Injection is a useful alternative to Service Locator. When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.
…
The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application.
In the draft chapter I mentioned in my previous post Dhanji R. Prasanna writes:
Unfortunately, being a kind of factory, service locators suffer from the same problems of testability (or lack thereof) and shared state. The keys used to identify a service are also opaque and can be quite confusing to work with (as anyone who has used JNDI can attest). If a key is bound improperly, then the wrong type of object may be created and this error is found out only at runtime. The practice of embedding information about the service within its key (viz., "JapaneseEmailerWithPhoneAndEmail") is also unclear and places too much emphasis on arbitrary conventions.
I don't think these points are particularly compelling: binding the key incorrectly need not be a concern if, instead of a key string, a type parameter or a generic type parameter is used — for an example see the API of the Common Service Locator library — and the actual type returned from a request to the Service Locator can be configured progammatically or via a configuration file.
But I intuitively prefer the use of DI to a Service Locator. It more clearly separates the two concerns of service configuration and use of the service. It is also potentially more flexible, in that you could have a DI container which could be configured to take into account the class of the component when supplying a particular type in the component's constructor (for example, say the component needed an instance of ILogger and the implementation of ILogger needed to know the type of the component it was going to be logging). In the case where the component needs to request services after its constructor has been called, the component can be supplied with an instance of a provider class.
Dependency Injection
I've become a big fan of Dependency Injection over the last few months. I was adding new functionality to a large .NET application which had not been designed with unit testing in mind and I found it difficult to create unit tests for the new components I was writing. I had to use a ServiceLocator type mechanism which could be configured during unit testing to supply mock types. Getting this into place required a substantial amount of work on top of the new functionality I was implementing. I am now using the Unity DI container on another project and finding that DI really does make a difference, separating the provision of services to classes from the functional structure of the application.
During this time I came across the Google Testing Blog. I found a lot of useful posts on here, particularly those by Miko Hevery, which helped clarify why the legacy code I was working with was so difficult to test.
Via Mike Hadlow, I discovered a couple of days ago that Dhanji R. Prasanna, another engineer at Google, is working on a book called Dependency Injection which looks interesting. A draft of the first chapter is available free online and is worth reading if you want an introduction to Dependency Injection.
Converting Locale ID (LCID) to Locale Name
While in the vicinity of System.Globalization, a quick tip, something I used the other day for the first time, on how to convert from a Locale ID, or LCID, to the corresponding locale name: just use the constructor of the CultureInfo class which takes an LCID:
CultureInfo ci = new CultureInfo(0x809);
Console.WriteLine(ci.Name);
Assert.AreEqual("en-GB", ci.Name);
And going the other way:
CultureInfo ci = new CultureInfo("en-GB");
Console.WriteLine("0x{0:X}", ci.LCID);
Assert.AreEqual(0x809, ci.LCID);
CurrentCulture and CurrentUICulture
While writing the post yesterday on Expression<TDelegate> another post from Brad Abrams in his Framework Design Guidelines series — Overriding Object.ToString() — triggered my curiosity, this time about the difference between CurrentCulture and CurrentUICulture:
DO string formatting based on the current thread culture when returning culture-dependent information.
To be more explicit, use the CultureInfo instance returned by a thread’s CurrentCulture property to format any numeric or date, and the one returned by CurrentUICulture to look up any resource. People are often confused between the two properties.
The difference seems to be that CurrentCulture is concerned with internationalization, determining how things such as numbers, currencies, dates, and time are formatted, whereas CurrentUICulture is concerned with localization, determining which language related resources are used to display text in dialogs, menus, etc.
The default value of CultureInfo.CurrentCulture is determined by the regional options for the current user. This is configured using the Regional Options tab in the Regional and Language Options Control Panel applet. On my machine with XP installed I have about 160 different regions to choose from, from Afrikaans to Zulu. The default value of CurrentCulture corresponds to Win32 GetUserDefaultLCID.
The default value of CultureInfo.CurrentUICulture is determined by the the configured UI language for the current user on an MUI version of Windows and the installed language for a localized version of Windows. The default corresponds to Win32 GetUserDefaultUILanguage. On a MUI version of Windows it is configured using the Languages tab of the Regional and Language Options applet.
There is also CultureInfo.InstalledUICulture. This is determined by the UI language for the installed version of Windows. It corresponds to Win32 GetSystemDefaultUILanguage.
CurrentCulture and CurrentUICulture can be set using the corresponding instance properties of the Thread class:
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
Note that there is no way of configuring the properties globally for an application. To use non-default values the properties must be explicitly set on every relevant thread.
So, assuming we have the appropriate resources attached to our assembly, we can specify the way numbers, currencies, dates, etc, are displayed independently of which language is used for our UI:
var resMan = new ResourceManager("TestCulture.TestCulture",
System.Reflection.Assembly.GetExecutingAssembly());
DateTime dateTime = new DateTime(2008, 12, 25);
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
string hello = resMan.GetString("Hello");
Console.WriteLine("{0}, {1:d}", hello, dateTime);
// displays "Bonjour, 25/12/2008"
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("{0}, {1:d}", hello, dateTime);
// displays "Bonjour, 12/25/2008"
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
hello = resMan.GetString("Hello");
Console.WriteLine("{0}, {1:d}", hello, dateTime);
// displays "Hi, 12/25/2008"
Expression<TDelegate> Class
Brad Abram's post Avoiding Custom Delegates, which I linked to in an earlier post, also mentions the Expression<TDelegate> class.
Expression<…> represents function definitions that can be compiled and subsequently invoked at runtime but can also be serialized and passed to remote processes.
Expression<TDelegate> takes a delegate type as its generic parameter and is created by assigning from a lambda expression.
using System.Collections.ObjectModel;
namespace System.Linq.Expressions
{
// Summary:
// Represents a strongly typed lambda expression as a data structure in the
// form of an expression tree. This class cannot be inherited.
//
// Type parameters:
// TDelegate:
// The type of the delegate that the System.Linq.Expressions.Expression<TDelegate>
// represents.
public sealed class Expression<TDelegate> : LambdaExpression
{
// Summary:
// Compiles the lambda expression described by the expression tree into executable
// code.
//
// Returns:
// A delegate of type TDelegate that represents the lambda expression described
// by the System.Linq.Expressions.Expression<TDelegate>.
public TDelegate Compile();
}
}
For example:
Expression<Func<int, bool>> exprTree = num => num < 5;
The compiler is implemented such that when it has to compile an assignment like this to Expression
Expression<Func<int, bool>> exprTree = num => num < 5;
// Decompose the expression tree.
ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
BinaryExpression operation = (BinaryExpression)exprTree.Body;
ParameterExpression left = (ParameterExpression)operation.Left;
ConstantExpression right = (ConstantExpression)operation.Right;
Console.WriteLine("Decomposed expression: {0} => {1} {2} {3}",
param.Name, left.Name, operation.NodeType, right.Value);
/*
console output is:
Decomposed expression: num => num LessThan 5
*/
The Compile method of Expression<TDelegate> can be called to create a delegate of the instance's generic type:
Func<int, bool> func = exprTree.Compile(); Assert.AreEqual(true, func(3));
The advantage of using Expression<TDelegate> is that if the methods of an API take instances of this instead of delegates, the implementation of the API can optimize the processing of the expression tree at runtime. For example, in Linq to SQL many of the methods of the IQueryable interface take Expression<TDelegate> so that optimized SQL can be generated at runtime. This can make a huge difference to the performance of Linq expressions.
Note that Expression<TDelegate> can only be assigned a lambda expression with an expression body. You cannot assign a lambda expression or an anonymous delegate:
// does not compile
Expression<Func<int, bool>> exprTree2 = num => { return num < 5; };
// does not compile
Expression<Func<int, bool>> exprTree3 = delegate(int num) { return num < 5; };