Unit testing methods which use global variables

c#, unit-testing

Solution

I would be tempted to have a separate overloaded method, then I could have one with the parameter and one without...

public string Baz()
{
    return Baz(GlobalVariable);
}

public string Baz(string globalVar)
{
    return globalVar + "qux";
}

The benefit here is that you still have your parameter-less method which can be called from code without you having to worry about specifying the value each time, but then you have the overload for testing and also in the event you do ever need to use a different value.

Although you still cannot test the first method using different values, I think it would be safe to assume testing the second function only would be enough.

Or, if you are using C# 4.0 you could use optional parameters instead:

public string Baz(string globalVar = null)
{
    if(string.IsNullOrEmpty(globalVar))
        globalVar = GlobalVariable;
    return globalVar + "qux";
}

Problem

Lets say I have the following class structure: ``` private string GlobalVariable = "foo"; public void MainMethod() { string bar = Baz(); } public string Baz() { return GlobalVariable + "qux"; } ``` I wish to carry out a unit test on `Baz()` using different values for `GlobalVariable`. However as `GlobalVariable` is simply called within the method, and not passed to it as a parameter, I cannot set this in my unit test method. Therefore I've considered changing my structure to: ``` private string GlobalVariable = "foo"; public void MainMethod() { string bar = Baz(GlobalVariable); } public string Baz(string globalVar) { return globalVar + "qux"; } ``` This way I can now change the parameter value `globalVar` in my unit tests in order to check different outputs. However, my first structure is more cleaner as I'm not unnecessarily passing variable values to methods as parameters. Is there a way of getting the best of both worlds, without having to hinder my structure in order to run unit tests?

Original source