views:

27

answers:

1

I am unit-testing a a .NET project using visual studio's own framework where each test needs to close certain connections so that the next test may run correctly. However, when a test fails, this cleanup is not performed, and as a result all subsequent tests fail.

Is there a way I can execute a method everytime a test fails?

+4  A: 

Try to put your cleanup logic into a method decorated by the [TestCleanUp] attribute.

See the MSDN for details.

Romain Verdier
How can I pass parameters to such a method? Also, ideally I would like to define a global variable at the [ClassInitialize] method, but it doesn't let me see the property I just defined. The property shows up in [TestCleanUp]. How come?
sbenderli
@sbenderli: You can't. It's similar to a [TestMethod] in that it's automatically located and called by the test engine. The [TestCleanup] method in a class is called *after* each test completes, to clean up. Likewise, the [TestInitialize] method is executed *before* each test to set up the pre-test state of the test fixture.
Toby
You can't, and you shouldn't. this method, as well as `TestInitialize`, is automatically called by the testing engine. You still can use fields of your test fixture class. i.e. You create a `_connection` member in your class, you initialize the connection in the `[TestInitialize]` method, then you close it in the `[TestCleanUp]` method.
Romain Verdier
@Romain, that's exactly what I did now and it's excellent for my purposes. Thanks!
sbenderli
Only do this if you connection member is used by all (/most) of your tests. If not try/finally blocks.
mlk