简体   繁体   中英

Is there a way to execute initializer code before each test in Visual Studio Unit Testing (MSTest) for all tests in a project?

I have a Unit Test project with 20+ .cs files. I want to run some setup code before each individual test. Kinda like how the [TestInitialize] attribute works. However, I'd need to put that attribute on all 20+ of my .cs files.

Is there a way to centralize the initializing code in one place for every test in my entire project?

Thanks!

-Mike

Mike the only bootstrapping hooks are [ClassInitialize] and [TestInitialize] and their teardown counterparts. In cases like these I just externalized the common logic into its own class, essentially follow normal DRY and SoC practices. Typically I have several services and providers defined within my test assemblies and the xInitialize methods just have 1 or 2 lines of code to call the approperiate provider. That being said mpistrich's answer is perfectly acceptable as well, I perfer layering over inheritence.

I don't know whether this is still an issue. But I found one more solution do achieve this: When opening the .testsettings file, go to the "Setup and Cleanup scripts" tab, you can specify scripts to run before and after the tests run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM