Skip to content

Test Environment Initialization

Alexander edited this page Apr 26, 2015 · 8 revisions

Overview

Quite often it happens that some of the tests share the same initialization routines. Most of the popular testing frameworks address this problem, but each in its own way. Sitecore.LiveTesting framework could have provided such common initialization routines for each of the popular frameworks, but since initialization is required in other scenarios apart from test execution, it was decided for Sitecore.LiveTesting to implement its own initialization workflow.
In Sitecore.LiveTesting initialization is performed by means of so-called initialization handlers and available only if the test class is derived from Sitecore.LiveTesting.Initialization.LiveTestWithInitialization. Initialization handler is a type an instance of which will be created before certain action and will be disposed on action completion if initialization handler implements System.IDisposable.
Let's now consider different scenarios of how initialization handlers can be used.

Test Initialization

The most obvious scenario to apply initialization handlers is test initialization and cleanup. Imagine that we have a web application and some part of its logic depends on the presence of environment variable and we would like to test what will happen if variable is available and what will be if not. Here is a short example of tests for these two scenarios:

using Sitecore.LiveTesting.Initialization;
using NUnit.Framework;

[TestFixture]
public class SampleTestWithInitialization : LiveTestWithInitialization
{
  private const string VariableName = "Variable";

  /* Without this initialization handler the following test would fail.
   * See constructor of the corresponding type for more details.     */
  [InitializationHandler(typeof(SampleInitializationHandler))]
  [Test]
  public void ShouldPerformActionBasedOnEnvironmentVariableValue()
  {
    this.MethodUnderTest();
  }

  /* This test would fail if initialization handler did not implement
   * System.IDisposable interface. See the implementation for more
   * details.                                                      */
  [Test]
  public void ShouldThrowExceptionIfEnvironmentVariableIsNotDefined()
  {
    Assert.Throws<System.InvalidOperationException>(this.MethodUnderTest);
  }

  private void MethodUnderTest()
  {
    string variable = System.Environment.GetEnvironmentVariable(VariableName);

    if (string.IsNullOrEmpty(variable)) 
    {
      throw new System.InvalidOperationException();
    }

    // Some application logic that depends on connection string data
  }

  private class SampleInitializationHandler : System.IDisposable
  {
    public SampleInitializationHandler() 
    {
      System.Environment.SetEnvironmentVariable(VariableName, "value");
    }

    public void Dispose()
    {
      System.Environment.SetEnvironmentVariable(VariableName, null);
    }
  }
}  

Now when it is clear what initialization handlers are designed for, let's consider the means by which they can be generalized in order to achieve their better reusability.
One of the simpliest ways to make initialization handler more generic is to introduce parameters. Here is how we could change the previous example (for brevity, only the changed methods are shown below):

[InitializationHandler(typeof(SampleInitializationHandler), VariableName)]
[Test]
public void ShouldPerformActionBasedOnEnvironmentVariableValue()
{
  this.MethodUnderTest();
}

...

private class SampleInitializationHandler : System.IDisposable
{
  private readonly string variableName;

  public SampleInitializationHandler(string variableName) 
  {
    this.variableName = variableName;
    System.Environment.SetEnvironmentVariable(this.variableName, "value");
  }

  public void Dispose()
  {
    System.Environment.SetEnvironmentVariable(this.variableName, null);
  }
}  

If one would like to make initialization handler extremely generic and receive a variable number of arguments, he can declare constructor in the following manner:

public SampleInitializationHandler(object[] arguments)  

or like

public SampleInitializationHandler(params object[] arguments)  

Note that most of Sitecore Switchers/Disablers satisfy the requirements for initialization handlers and can easily be used with no additional efforts.
The one thing that can make initialization handlers even more powerful is the ability to retrieve context of initialization. In order to do so the handler must implement Sitecore.LiveTesting.Initialization.IInitializationContextAware interface. Just after the handler instantiation the only method of the interface will be called with the object that represents current initialization context. Sitecore.LiveTesting.Initialization.TestInitializationContext is the type of context object when initialization is run for a test.
Even though there is not much practical sense in it, here is a small example of initialization handler which concatenates all test method arguments and writes the result into the field of test fixture:

using Sitecore.LiveTesting.Initialization;
using NUnit.Framework;

[TestFixture]
public class SampleTestWithInitialization : LiveTestWithInitialization
{
  public string Field;

  [InitializationHandler(typeof(SampleContextAwareInitializationHandler))]
  [TestCase("a", 2, "c")]
  public void TestMethod(string a, int b, string c)
  {
    Assert.AreEqual("a2c", this.Field);
  }

  private class SampleContextAwareInitializationHandler : IInitializationContextAware
  {
    public void SetInitializationContext(object context)
    {
      ((SampleTestWithInitialization)((TestInitializationContext)context).Instance).Field = 
        string.Concat(((TestInitializationContext)context).Arguments);
    }
  }
}  

Request Initialization

Initialization handlers can also be used to perform basic initialization for request environment. Consider a situation when we would like to test our custom http handler, but have not registered it yet and for this reason want to bypass the process of http handler search. Here is how it can be done with an empty web application having no pages at all:

using Sitecore.LiveTesting.Initialization;
using NUnit.Framework;

[TestFixture]
public class SampleTestWithInitialization : LiveTestWithInitialization
{
  [Test]
  public void TestMethod()
  {
    Sitecore.LiveTesting.Requests.Request request = new Sitecore.LiveTesting.Requests.Request 
      { 
        Path = "non-existent-url",
        InitializationHandlers = 
          { 
            new InitializationHandler(typeof(SampleRequestInitializationHandler))
          } 
      };
    Sitecore.LiveTesting.Requests.RequestManager requestManager = 
      new Sitecore.LiveTesting.Requests.RequestManager();

    Sitecore.LiveTesting.Requests.Response response = requestManager.ExecuteRequest(request);

    Assert.AreEqual(200, response.StatusCode);
    Assert.AreEqual("Response", response.Content);
  }

  private class SampleHttpHandler : System.Web.IHttpHandler
  {
    public bool IsReusable 
    {
      get { return false; }
    }

    public void ProcessRequest(System.Web.HttpContext context)
    {
      context.Response.Write("Response");
    }
  }

  private class SampleRequestInitializationHandler : IInitializationContextAware
  {
    public void SetInitializationContext(object context)
    {
      ((RequestInitializationContext)context).HttpContext.RemapHandler(new SampleHttpHandler());
    }
  }
}  

Another good example of request initialization handler use may be emulation of authentication process. You can find ready to use solution for authentication of Sitecore users in Sitecore.LiveTesting.Extensions.Request.AuthenticatedRequest class. This type also shows how request initialization handlers can be parametrized and combined together.
There is one more point worth to note - all request-related event handlers described in Global.asax file are executed after corresponding request initialization handler beging created, but before it will be disposed.

Test Application Initialization

Apart from test method and request initialization it is possible to perform test application-wise initialization. This means that initialization handler is created just after test application has started and will be disposed just before it ends. In order to specify such initialization handlers, one should apply Sitecore.LiveTesting.Initialization.InitializationHandlerAttribute to the test assembly. Here is an example:

[assembly: InitializationHandler(typeof(SampleTestApplicationInitializationHandler)]  

In relation to the application-related events defined in Global.asax file it can be said that application-level initialization handler will be created before Application_Init and Application_Start events (since these events are likely to be triggered by the first request issued by Sitecore.LiveTesting.Requests.RequestManager), but will also be disposed before Application_End and Application_Disposed events. One should also note, that all infrastructure around Global.asax is tied to request processing, and therefore it will not be invoked automatically before your tests run, unless you explicitly execute a request in one of the initialization handlers which creation precedes test execution.

Clone this wiki locally