<p>So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests.  I believe it--my code is difficult to test right now.  So how do I avoid global state?</p>

<p>The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments.  For example, I have a static class named "Globals" with a static member called "DBConnectionString."  When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString.  I load file paths, server names, and other information in the Globals class.</p>

<p>Some of my functions rely on the global variables.  So, when I test my functions, I have to remember to set certain globals first or else the tests will fail.  I'd like to avoid this.</p>

<p>Is there a good way to manage state information?  (Or am I understanding global state incorrectly?)</p>

[{'answer_id': 44375, 'author': 'Andrew', 'author_id': 826, 'author_profile': 'https://Stackoverflow.com/users/826', 'pm_score': 5, 'selected': True, 'text': "<p>Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate.</p>\n\n<p>It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection.</p>\n\n<p>Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation.</p>\n"}, {'answer_id': 44419, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 1, 'selected': False, 'text': '<p>Great first question.</p>\n\n<p>The short answer: make sure your application is a function from ALL its inputs (including implicit ones) to its outputs.</p>\n\n<p>The problem you\'re describing doesn\'t seem like global state. At least not mutable state. Rather, what you\'re describing seems like what is often referred to as "The Configuration Problem", and it has a number of solutions. If you\'re using Java, you may want to look into light-weight injection frameworks like <a href="http://code.google.com/p/google-guice/" rel="nofollow noreferrer">Guice</a>. In Scala, this is usually solved with <a href="http://www.google.com/search?q=scala+implicits" rel="nofollow noreferrer">implicits</a>. In some languages, you will be able to load another program to configure your program at runtime. This is how we used to configure servers written in Smalltalk, and I use a window manager written in Haskell called Xmonad whose configuration file is just another Haskell program.</p>\n'}, {'answer_id': 44558, 'author': 'JC.', 'author_id': 3615, 'author_profile': 'https://Stackoverflow.com/users/3615', 'pm_score': 2, 'selected': False, 'text': '<p>Keep in mind if your tests involve actual resources such as databases or filesystems then what you are doing are <em>integration tests</em> rather than <em>unit tests</em>. Integration tests require some preliminary setup whereas unit tests should be able to run independently.</p>\n\n<p>You could look into the use of a dependency injection framework such as Castle Windsor but for simple cases you may be able to take a middle of the road approach such as:</p>\n\n<pre><code>public interface ISettingsProvider\n{\n    string ConnectionString { get; }\n}\n\npublic class TestSettings : ISettingsProvider\n{        \n    public string ConnectionString { get { return "testdatabase"; } };\n}\n\npublic class DataStuff\n{\n    private ISettingsProvider settings;\n\n    public DataStuff(ISettingsProvider settings)\n    {\n        this.settings = settings;\n    }\n\n    public void DoSomething()\n    {\n        // use settings.ConnectionString\n    }\n}\n</code></pre>\n\n<p>In reality you would most likely read from config files in your implementation. If you\'re up for it, a full blown DI framework with swappable configurations is the way to go but I think this is at least better than using Globals.ConnectionString.</p>\n'}, {'answer_id': 21470841, 'author': 'Abul Fayes', 'author_id': 2678413, 'author_profile': 'https://Stackoverflow.com/users/2678413', 'pm_score': 0, 'selected': False, 'text': '<p>An example of dependency injection in an MVC setting, here goes:</p>\n\n<p>index.php</p>\n\n<pre><code>$container = new Container();\ninclude_file(\'container.php\');\n</code></pre>\n\n<p>container.php</p>\n\n<pre><code>container.add("database.driver", "mysql");\ncontainer.add("database.name","app");\n</code></pre>\n\n<p>...</p>\n\n<pre><code>$container.add(new Database($container-&gt;get(\'database.driver\', "database.name")), \'database\');\n$container.add(new Dao($container-&gt;get(\'database\')), \'dao\');\n$container.add(new Service($container-&gt;get(\'dao\')));\n$container.add(new Controller($container-&gt;get(\'service\')), \'controller\');\n\n$container.add(new FrontController(),\'frontController\');\n</code></pre>\n\n<p>index.php continues here:</p>\n\n<pre><code>$frontController = $container-&gt;get(\'frontController\');\n$controllerClass = $frontController-&gt;getController($_SERVER[\'request_uri\']);\n$controllerAction = $frontController-&gt;getAction($_SERVER[\'request_uri\']);\n$controller = $container-&gt;get(\'controller\');\n$controller-&gt;$action();\n</code></pre>\n\n<p>And there you have it, the controller depends on a service layer object which depends on \na dao(data access object) object which depends on a database object with depends on the\ndatabase driver, name etc</p>\n'}]
['https://Stackoverflow.com/questions/44364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/681/']