Skip to content

Advanced Lifecycle Options

Robert Coltheart edited this page May 6, 2019 · 8 revisions

The following lifecycle options should be used sparingly and with great purpose and deliberation.

IAssemblyContext

You can implement IAssemblyContext in your spec assembly to set things up before or clean things up after all of your specs in that assembly have run.

public class CultureSensitiveTests : IAssemblyContext
{
    private static readonly CultureInfo Original = Thread.CurrentThread.CurrentCulture;
    private static readonly CultureInfo Deutsch = new CultureInfo("de-DE");

    public void OnAssemblyStart()
    {
        Thread.CurrentThread.CurrentCulture = Deutsch;
        Thread.CurrentThread.CurrentUICulture = Deutsch;
    }

    public void OnAssemblyComplete()
    {
        Thread.CurrentThread.CurrentCulture = Original;
        Thread.CurrentThread.CurrentUICulture = Original;
    }
}

ICleanupAfterEveryContextInAssembly

You can implement ICleanupAfterEveryContextInAssembly to perform cleanup after every context. For example, if you had a testable, static system clock

public static class SystemClock
{
    public static Func<DateTime> Now = () => DateTime.Now;
}

That you modified for certain tests

Establish = () =>
    SystemClock.Now = () => DateTime.Now.AddDays(-3);

You would want to reset the clock after every context, rather than remembering to write the paired Cleanup statement every time.

public class ResetTheClock : ICleanupAfterEveryContextInAssembly
{
    public void AfterContextCleanup()
    {
        SystemClock.Now = () => DateTime.Now;
    }
}

SetupForEachSpecification

The context is always established once. Observations are observations. They should not mutate state. So, there is no reason to execute the context more than once.

If you really want to execute the context for each specification, first try to change your mind... Then, if you still want it, use [SetupForEachSpecification] on your class.

[SetupForEachSpecification]
[Subject("Ignoring Good Advice")]
class When_not_listening_to_the_guidance { ... }