简体   繁体   中英

Clear all static data after each test case in MSTest

I wan to write tests for my library with MSTest. After TestCase1 runs, it does somethings, set MyData (private static field of my library's internal class) like:

internal MyClass{private static int MyData;}

When TestCase2 runs, it will re-use that data.

I have written a Reset method and call it in TestInitialize method content like:

var type = MyAssembly.GetType("MyClass");
var privateType = new PrivateType(type);
privateType.SetStaticField("MyData", 0);

As you see, the method will reset the static field to 0 but it need to know the name of attribute and class ("MyClass" and "MyData").

Now, I test with my obfuscated dll, the test will fail because the name will be changed. Besides, in side my library, i reference to third party libraries, it may store data in static fields also. It will make the TestCase2 re-used data that was set by TestCase1 and TestCase2 will always fail.

How can i reset all static fields at TestInitialize?

** UPDATE:

I can see a solution that i can run each test case on a separate AppDomain, it may slow but i may try. The issue is i don't know how to run each test case in a separated AppDomain correctly?

I found NO better solution after days of reading documents and examples. I have discussed with some colleagues and i think it should be an issue of my tested library's design, not an issue of my test design.

Saving data in library static field and change it will keep that data coupled with the running process or instance. In real life, if user run 2 (or more) processes (instances) of application that use the library, that static data will easily be changed in an unpredictable way and a huge disaster comes. So, solving my test issue by clearing static data is just a "let the code go" trick and that tricky solution hides the real issue inside the code - more dangerous.

Saving data in a static field is really BAD idea . DON'T do this if that data is NOT STATIC.

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