Running code on assembly load in xUnit

本秂侑毒 提交于 2019-12-08 17:26:14

问题


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:


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.



来源:https://stackoverflow.com/questions/30730224/running-code-on-assembly-load-in-xunit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!