Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio Unit Testing: SetUp and TearDown

Instead of [SetUp] and [TearDown] in Nunit what is the alternative in Visual Studio Ultimate 2010 Unit Testing. In Nunit you can imagine setup and teardown methods are as constructors and destructors for the tests in our class.

like image 599
Etibar - a tea bar Avatar asked Jan 22 '13 15:01

Etibar - a tea bar


People also ask

What is setUp and tearDown in unit test?

When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.

Where will you use setUp () and tearDown () methods?

Prepare and Tear Down State for a Test Class XCTest runs setUp() once before the test class begins. If you need to clean up temporary files or capture any data that you want to analyze after the test class is complete, use the tearDown() class method on XCTestCase .

What are setUp () and tearDown () methods in mobile app testing?

For that it has two important methods, setUp() and tearDown() . setUp() — This method is called before the invocation of each test method in the given class. tearDown() — This method is called after the invocation of each test method in given class.

How do I create a unit test in Visual Studio?

From the code editor window, right-click and choose Create Unit Tests from the right-click menu. The Create Unit Tests menu command is only available for C# code. To use this method with . NET Core or .


2 Answers

A method annotated with [TestInitialize] is run before each test. Likewise [TestCleanup] is after each test.

[ClassInitialize] and [ClassCleanup] are run before and after the 'suite' of tests inside the TestClass.

like image 159
Mikeb Avatar answered Sep 30 '22 14:09

Mikeb


Visual Studio will use MSTest, that is Microsoft's unit testing framework, it is similar to NUnit. In fact, most of them are similar in concepts but different syntax.

In order to view the comparaison, the creators of xUnit (another unit testing framework) have a list here:

https://xunit.net/docs/comparisons

More specifically what you asked for, TestInitialize is MSTest's equivalent to NUnit's Setup, and the same for TestCleanup and TearDown.

One thing to note, I would stay with NUnit if you are attempting to do automated unit testing or some kind of continuous integration. The main reason the various *unit frameworks are favoured over MSTest is because you must have a copy of Visual Studio on the machine you are running the tests on. Fine for your own local machine, different story for a CI server. Visual Studio is a pig of a program, and to install it on a server (which is generally supposed to be as lightweight and fast as it can be), just to run tests is a bit annoying.

like image 39
Arran Avatar answered Sep 30 '22 13:09

Arran