Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MsTest - executing method before each test in an assembly

Tags:

.net

mstest

Is it possible to run specific method before each test in an assembly?

I know about TestInitialize attribute but this attribute has "class scope". If it's defined in a Test class it will be executed before each test from this class.

I want to define a method that will be executed before each test defined in a whole assembly.

like image 732
brzozow Avatar asked Mar 12 '09 16:03

brzozow


People also ask

Does TestInitialize run for each test?

TestInitialize and TestCleanup are ran before and after each test, this is to ensure that no tests are coupled. If you want to run methods before and after ALL tests, decorate relevant methods with the ClassInitialize and ClassCleanup attributes.

How do I run a MSTest unit test?

To run MSTest unit tests, specify the full path to the MSTest executable (mstest.exe) in the Unit Testing Options dialog. To call this dialog directly from the editor, right-click somewhere in the editor and then click Options.

Which among the following is the correct command to install test framework packages in MSTest?

You can download and install the MSTest framework by either of the two methods, as shown below: a. PM (Package Manager) commands from the ''NuGet Package Manager Console” – For executing commands from the NuGet PM console, go to 'Tools' -> 'NuGet Package Manager' -> 'Package Manager Console.


2 Answers

[TestInitialize()] is what you need.

private string dir;  [TestInitialize()] public void Startup() {     dir = Path.GetTempFileName();     MakeDirectory(ssDir); }  [TestCleanup()] public void Cleanup() {     ss = null;     Directory.SetCurrentDirectory(Path.GetTempPath());      setAttributesNormal(new DirectoryInfo(ssDir));     Directory.Delete(ssDir, true); }   [TestMethod] public void TestAddFile() {     File.WriteAllText(dir + "a", "This is a file");     ss.AddFile("a");     ... }  [TestMethod] public void TestAddFolder() {     ss.CreateFolder("a/");     ... } 

This gives a new random temporary path for each test, and deletes it when it's done. You can verify this by running it in debug and looking at the dir variable for each test case.

like image 124
FryGuy Avatar answered Oct 01 '22 11:10

FryGuy


I am not sure that this feature is possible in MsTest out of box like in other test frameworks (e.g. MbUnit).

If I have to use MsTest, then I am solving this by defining abstract class TestBase with [TestInitialize] attribute and every test which needs this behaviour derives from this base class. In your case, every test class in your assembly must inherit from this base...

And there is probably another solution, you can make your custom test attribute - but I have not tried this yet... :)

like image 28
nihique Avatar answered Oct 01 '22 10:10

nihique