开发者

Is it a BAD idea to have a static connection and transaction for a Unit Test Fixture?

开发者 https://www.devze.com 2023-04-07 10:16 出处:网络
I plan to create static private variables for SqlConnection and SqlTransaction which I plan to create in [ClassInitialize()] signed method and then dispose in [ClassCleanup] signed methods.

I plan to create static private variables for SqlConnection and SqlTransaction which I plan to create in [ClassInitialize()] signed method and then dispose in [ClassCleanup] signed methods.

What I want to achieve is to share the connection and transaction all along the tests and then roll back everything in the end of the last unit test run.

Like below.

Is this a BAD idea? Should I worry about thread safety?

        [ClassInitialize()]
        public static void DataManagerTestInitialize(TestContext testContext)
        {

            // Create Connection for Test Fixture
            _connection = new SqlConnection(ConnectionString);

            // Open Connection for Test Fixture
            _connection.Open();

            // Open Transaction for Test Fixture
            _transaction = _connection.BeginTransaction();

}

  [ClassCleanup]
        public static void CleanUp()
        {
            if(_transaction!=null)
                _transact开发者_如何转开发ion.Rollback();

            if(_connection.State != ConnectionState.Closed)
                _connection.Close();
        }


This is a bad idea. Connections are meant to be opened - used - then closed. The same goes for transactions. Besides - your tests should be independent of each other and sharing a connection / transaction violates this principle.


You should worry about locks in the database if someone is debugging a specific unit test. If the database you use is the same database as your development occurs on this can be very frustrating when you're developing something (for example) and performance is really bad or he even gets timeouts because of someone putting locks on the database.

If you don't want to change your database (which you don't when unit testing) you should be able to mock/replace the code that hits the database. There are several ways to achieve this but my favorite is to use Dependency Injection. This makes your application a lot easier to maintain as it forces you to think carefully about what methods are exposed by the various parts of your application. Plus the abstraction will make it easier to refactor.

0

精彩评论

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

关注公众号