The perils of sharing state when writing tests
Tags: testing, csharp, dotnet
Published: 2019-11-06 10:17:38

<p>Sharing state is always a bad idea. Functional programmers have been using immutability for a long time now, completely avoiding the perils this can bring.</p>



<p>For all the others that for one reason or another keep going on with the good ol’ OOP, this is an hard lesson that needs to be learned. And sooner is the better.</p>



<p>Moreover, this is true for tests as well. They are a piece of software too, and as such they deserve the same care and respect we give to the rest of our applications.</p>



<h3>Let me say that again. Never. Share. State.</h3>



<p>As usual Martin Fowler has <a rel="noreferrer noopener" aria-label="a nice article (opens in a new tab)" href="https://martinfowler.com/bliki/AliasingBug.html" target="_blank">a nice article</a> about references and immutable objects. Make sure to check it out, I’ll wait.</p>



<p>Now let’s go back to the tests problem. The standard setup for unit tests is to: </p>



<ol><li>mock whatever dependencies your <a href="https://blogs.msdn.microsoft.com/ploeh/2008/10/06/naming-sut-test-variables/" target="_blank" rel="noreferrer noopener" aria-label="SUT (opens in a new tab)">SUT</a> has </li><li>configure them </li><li>instantiate the SUT</li><li>test and assert</li></ol>



<p>Now the problem lies in points 1 and 3. Well, <strong>might</strong> lie there.</p>



<figure class="wp-block-image alignwide"><img src="https://i0.wp.com/www.ilmessaggero.it/photos/MED/84/49/4638449_1940_replicante.jpg?zoom=1.25&amp;w=788&amp;ssl=1" alt="This image has an empty alt attribute; its file name is 4638449_1940_replicante.jpg" data-recalc-dims="1" width="650" height="355" src-orig="https://i0.wp.com/www.ilmessaggero.it/photos/MED/84/49/4638449_1940_replicante.jpg?w=788&amp;ssl=1" scale="1.25"><figcaption>I have seen things…</figcaption></figure>



<p>There are cases where you might be tempted to declare the SUT and its dependencies as class members. This will surely simplify the setup as you can initialize everything in the test class cTor.</p>



<p>It’s tempting, I know. I’ve been there.</p>



<p>Maybe you want to get a step further and declare them as <strong>static</strong>. Why not, we’re reusing them and we don’t want to waste precious time instantiating stuff over and over.</p>



<p>Well if you do, keep in mind that those instances are shared, so every setup you do on the dependencies for example, will be reused by all the tests in that class.</p>



<p>Let’s say for example that you’re instructing a dependency to throw an exception in order to catch it in the SUT and handle it properly. You’re asserting this in a test, but what all the other tests? They’ll get the exception too.</p>



<p>I think you’re starting to see the point here.</p>



<p>As usual, I’ve created a micro-repository showing the idea. You can <a rel="noreferrer noopener" aria-label="find it here (opens in a new tab)" href="https://github.com/mizrael/isolated-tests/" target="_blank">find it here</a>.</p>



<p>All in all this might seem a minor thing, but trust me, sooner or later you’ll be in the situation where a test passes when executed alone and fails when you run all the suite. Now, <strong>that</strong> is a typical case of shared state. Keep an eye on the symptoms! </p>



<p>Personally, I’m a great fan of <a href="https://xunit.net/">xUnit</a>. It has some very nice features, but this is one of my favorites (directly <a rel="noreferrer noopener" aria-label="from the docs (opens in a new tab)" href="https://xunit.net/docs/shared-context" target="_blank">from the docs</a>) :</p>



<blockquote class="wp-block-quote"><p>“xUnit.net&nbsp;creates a new instance of the test class for every test that is run, so any code which is placed into the constructor of the test class will be run for every single test”</p></blockquote>



<p>This will basically save you as it will create a fresh context for every test.</p>



<p>Now of course this doesn’t apply much to persistence and integration tests. In that case you’re <strong>expecting</strong> a db to be provisioned and accessible. But again, in that case it would be much better if you rely on a Fixture (or whatever your library of choice has).</p>



<p>A much better strategy would be to generate the db dynamically for each test and drop it at the end.  If you’re running on a CI/CD platform (like Gitlab or Travis), you can even spin up a Docker container with the db server. I might write a post one of these days and elaborate more.</p>



<p>Going back to the code, if you take a look at the <a rel="noreferrer noopener" aria-label="BetterTests class (opens in a new tab)" href="https://github.com/mizrael/isolated-tests/blob/master/tests/BetterTests.cs" target="_blank">BetterTests class</a> you’ll see that I’m defining a static factory method for the SUT, but with a twist: it’s accepting “configuration functions” as arguments. The factory method will instantiate the mock dependencies, then use those functions to configure them with whatever is passed from the consumers.</p>



<p>So in one case, we’re building a dependency that throws, while in another we’re just accepting the instance and nothing else.</p>



<p>Pretty neat, isn’t it?</p>



<p>Don’t forget to take a look at my series on <a href="https://www.davideguida.com/lets-do-some-ddd-with-entity-framework-core-3/" target="_blank" rel="noreferrer noopener" aria-label="DDD and Entity Framework Core (opens in a new tab)">DDD and Entity Framework Core</a>!</p>