Geeks With Blogs

News This is the *old* blog. The new one is at blog.sixeyed.com
Elton Stoneman
This is the *old* blog. The new one is at blog.sixeyed.com

For automated integration tests, you often have external dependencies that you need to start up before the test run, and teardown after the test run.

If you’re firing up a stub service, deploying a database, or starting a bunch of NServiceBus hosts, that can be expensive. You don’t want to do it in the test setup, as it’ll make all the tests longer to run. Ideally you want to run the startup once before any test starts, and then run the teardown once after all tests have finished.

Visual Studio doesn’t let you do this in a nice way which is consistent with local test runs and build server runs, but if your integration tests are all in one project, you can do it with the AssemblyInitialize and AssemblyCleanup attributes.

Simple example:

    [TestClass]
    public sealed class DependencySetup
    {
        [AssemblyInitialize]
        public static void Start(TestContext context)
        {
            Process.Start("StartDependencies.cmd");
            Thread.Sleep(1000);
        }

        [AssemblyCleanup]
        public static void Stop()
        {
            KillProcessInstances("Stub");
            KillProcessInstances("NServiceBus.Host");
        }

        private static void KillProcessInstances(string friendlyName)
        {
            var processes = Process.GetProcessesByName(friendlyName);
            foreach (var process in processes)
            {
                process.Kill();
            }
        }
    }

The static Start method will get called once before any tests in the assembly execute, and the static Stop method gets called once after all the tests in the assembly have completed (pass, fail or inconclusive). Note that the class needs to be decorated with the TestClass attribute for the static methods to be found.

This approach works for test runs from Visual Studio and MSBuild, and any other tools which execute tests, like ReSharper test sessions.

Posted on Wednesday, December 11, 2013 5:15 PM Code Snippet , MSBuild , Unit Testing | Back to top


Comments on this post: How to setup and teardown integration test dependencies

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Elton Stoneman | Powered by: GeeksWithBlogs.net