xUnit - Cleaning side effects

xUnit - Cleaning side effects

I have been working with the file system last few days. As a part of this work, I create directories and files in the file system using code. When it came to unit testing my code, I used the System.IO.Abstractions.TestingHelpers library to mock the file system in my unit tests. System.IO.Abstractions.TestingHelpers package provides a mock file system with all the methods. Because this package uses an in-memory file system, I didn't need to clean up after. Using an in-memory file system meant I could also make my tests run faster.

But for integration testing, I decided to use the file system(actual), which meant creating directories and files during test runs which I needed to clean up after tests. Because I use xUnit, I needed to do the clean up using one of the following ways.

xUnit has excellent documentation with examples for each, which you could look into if you are interested in implementing any of those mentioned above. I used Constructor and Dispose method because I needed to clean up after each test. Unfortunately for me, this caused another issue. Because I created unique names for the files inside the tests, I could not delete files created during the test in the dispose method. So, in the dispose method, I decided to delete every file inside the folder where files get created. Due to this and because xUnit runs tests in parallel, some tests failed during the execution.

Running unit tests in parallel is a new feature in xUnit.net version 2. There are two essential motivations that drove us to not only enable parallelization but also for it to be a feature that's enabled by default.

From xUnit Documentation

Luckily for me, we can configure the default behaviour by setting parallelizeTestCollections property to false in the xunit.runner.json file. Not running tests in parallel meant my tests are taking longer to run now. But because these are integration tests, I decided to accept the time penalty to keep the tests simple.


Did you find this article valuable?

Support Dilan Livera by becoming a sponsor. Any amount is appreciated!