0

I have an utility method creating TransactionScope in my application.

I want to do a unit test to validate that the returned TransactionScope has the correct IsolationLevel set, to be sure that nobody can modify the code without breaking the tests.

System.Transactions.Transaction scope does not have public properties exposing information like that. (http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx)

Any way to get this information?

Normand Bedard
  • 2,625
  • 2
  • 19
  • 22

1 Answers1

2

Can you run a SQL query to check the isolation level:

SELECT CASE transaction_isolation_level 
WHEN 0 THEN 'Unspecified' 
WHEN 1 THEN 'ReadUncomitted' 
WHEN 2 THEN 'Readcomitted' 
WHEN 3 THEN 'Repeatable' 
WHEN 4 THEN 'Serializable' 
WHEN 5 THEN 'Snapshot' END AS IsolationLevel 
FROM sys.dm_exec_sessions 
where session_id = @@SPID

EDIT

Based on the comments below, there's also a way to get the isolation level from the code. This could be something like that:

using (TransactionScope scope = new TransactionScope())
{
    using (SqlConnection connection1 = new SqlConnection("Data Source=localhost;Integrated Security=True"))
    {
        Transaction trans = Transaction.Current;
        System.Transactions.IsolationLevel level = trans.IsolationLevel;
    }
}

You can get the current transaction by calling Transaction.Current.

Source: Implementing an Implicit Transaction using Transaction Scope

Szymon
  • 42,577
  • 16
  • 96
  • 114
  • So I'm not sure what you want to unit test... Are you mocking the database connection? – Szymon Oct 01 '13 at 11:05
  • I have a utility method that return a TransactionScope with some hardcoded settings like the timeout value and the isolation level. I want a unit test validating that the returned TransactionScope instance is correctly construct. This is a fail-safe to be sure that if someone made some modification to this code, a test will break. – Normand Bedard Oct 01 '13 at 11:21