I’m going to show how to perform integration test on an asynchronous method using Unit Test framework in Visual Studio 2015 using transaction scope.
The idea is running each test method in a transaction scope and disposing it at the end of the test instead of completing the transaction. This will roll back any changes to the database made by the test.
First, we create an abstract test base class which other test classes will inherit from. This base class contains a private transaction scope which is initialised during test initialisation and disposed during test clean up.
[TestClass] public abstract class BaseTest { /// <summary> /// The transaction scope. /// </summary> private TransactionScope transactionScope; /// <summary> /// The initialise. /// </summary> [TestInitialize] public virtual void Initialise() { this.transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); } /// <summary> /// The clean up. /// </summary> [TestCleanup] public void CleanUp() { this.transactionScope.Dispose(); } }
Notice that during the transaction initalisation, the transaction scope async flow option is set to enabled. This enables transaction flow across thread continuations. This makes transaction scope work with async methods.
Next is the test method. Since Visual Studio 2012, async task unit tests should just work without having to use GetAwaiter().GetResult() or Wait(). This makes it very simple. All it needs is putting async Task in the test signature and call async methods in the tests with the ‘await’ keyword.
[TestClass] public class TestAsyncTests : BaseTest { [TestMethod] public async Task SampleTest() { // Call async method with the 'await' keyword var result = await GetCurrentDateTimeAsync(); result.Should().NotBeNull(); } }
And that’s how you set up integration tests for asynchronous methods using transaction scope in Visual Studio 2015.
Simply awesome man! This is a simple approach to a complicated process.