Running code on assembly load in xUnit

3.3k views Asked by At

I am using the Effort library as a mock database, and it has some initialization code that has to run on assembly load.

I have tried adding this initialization code in a static constructor that is referenced from every test via a base class constructor but this did not meet the requirements of the library.

An answer to a similar question here mentions an AssemblyInitialize attribute, but this is not applicable to xUnit - xUnit has no way of running code on assembly load.

I also asked on the xUnit GitHub pages - there is definitively no assembly level initializer.

How can I run the initialization code that I need to in xUnit?

1

There are 1 answers

2
Alex On BEST ANSWER

I'm answering my own question because I've been trying to sort this out for weeks and have finally found a solution that works.

It's a third-party standalone package called Module Initializer. There's a NuGet package that's simple to use: install the package in your project, and the install script will create a file called ModulerInitializer.cs. It will also add a post-build step to the project file which will inject the code in ModuleInitializer.Run() into the module initializer. This is "guaranteed to run before any other code in the module runs, before any type initializers, static constructors or any other initialization code".

In practice this means that all you have to do is install the package and write the setup code - it really couldn't be more straightforward. Kudos to all involved.


There is also a promising-looking library called Fody.ModuleInit. However, this is a plugin for a more complex assembly weaving library - in my case the simpler solution was more appropriate.