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.
精彩评论