Unit Testing Part 2: Additional Test Attributes
|
by Holger Adam on 08/19/2011 | 0 Comments | 916 Views
|
This is part 2 of my series about unit testing. The first part covered the different assertion methods and can be found here. This part will cover additional test attributes.
Ever stumbled across a unit test that was encapsulated into code like this?
[TestMethod] private void MyUnitTest() { string tempPath = Path.GetTempFileName(); try { // ... test goes here } finally { if (String.IsNullOrEmpty(tempPath) == false) { File.Delete(tempPath); } } }
Now suppose that every test in the test class had the same structure. Not very elegant, because it adds a lot of duplicate code and another level of nesting. There is a better for situations like this which is kind of hidden in unit tests automatically generated by Visual Studio:
The name may be a little confusing, but these attributes are a pretty useful feature. Basically they are just four methods. What makes them special are the attributes (hence the name, I guess) [ClassInitialize], [ClassCleanup], [TestInitialize] and [TestCleanup] above the method declarations. They will let these methods be executed either before and after all of the tests in the test class or before and after each test method. This provides a framework of setting up the unit test environment for the entire test class and every test as needed.
Knowing this the example above can be transformed as follows. The MyTestInitialize method sets up the temporary file for the test and MyTestCleanup deletes it afterwards. The path to the file is a class variable known to all test methods and the construct delivers a defined environment for every test method.
private string _tempPath; // // Use TestInitialize to run code before running each test [TestInitialize] public void MyTestInitialize() { _tempPath = Path.GetTempFileName(); } // // Use TestCleanup to run code after each test has run [TestCleanup] public void MyTestCleanup() { if (String.IsNullOrEmpty(_tempPath) == false) { File.Delete(_tempPath); } } [TestMethod] private void MyUnitTest() { // ... test goes here }
The next part of this series will cover waiting for background threads.
- ‹ previous
- 17 of 21
- next ›
+++ Profile Migrator 2 - Ein neuer Desktop, ein frisches Benutzerprofile und alle bewährten Einstellungen und Daten. Jetzt kostenlos und unbefristet testen!
Aktuelle Artikel
Über den Autor
![]() |
Holger Adam Software Engineer Blogs about C++, C#, WPF, PowerShell and other things |








Add Comment