开发者

Passing parameters in TestCleanup

开发者 https://www.devze.com 2023-03-25 11:03 出处:网络
I want to perfor开发者_开发技巧m TestCleanup in my unit tests but I need to pass a parameter to the clean-up method. But since the default TestCleanup is called automatically I am not able to pass any

I want to perfor开发者_开发技巧m TestCleanup in my unit tests but I need to pass a parameter to the clean-up method. But since the default TestCleanup is called automatically I am not able to pass any parameters to it.

Can somebody please suggest a way to do this?


You could use a test class instance variable to communicate between the setup, test, and cleanup test methods:

namespace YourNamespace
{
    [TestClass]
    public class UnitTest1
    {
        private string someValue;

        [TestMethod]
        public void TestMethod1()
        {
            someValue = "someValue";
        }

        [TestCleanup]
        public void CleanUp()
        {
            // someValue is accessible here.
        }
    }
}

Since the the CleanUp() method will run after every unit test, someValue will be bound to the correct unit test's context.

Hope this helps.


You could set a field in the test class with the value the parameter you think you need to pass it should have, but to be honest it is surprising that you need some parameter to the clean up, and for me at least this would be a smell that something is wrong with the tests.

Your unit tests should not require clean up, each test should be responsible for doing its own setup and should run in isolation.

If you have integration tests which have some external dependencies which require some clean up, then you can either use a field as I suggested (which you would probably set at the beginning of each test (so that the clean up function would know what to clean up if the test failed) to be the correct value to clean up after that test) or I would make an explicit clean up function (which took the required parameter) which was called by each test explicitly at the end, and then have the TestFixture clean up ensure that it cleaned up ALL data which may have been used by ANY of the tests in case any of them failed without calling their clean up method.

0

精彩评论

暂无评论...
验证码 换一张
取 消