Skip to content

Test Context Setup

Tom Longhurst edited this page May 1, 2020 · 2 revisions

Test Context

BDTest will take care of your test context objects for you. Tests will have a context constructed for each test, and they will not be visible to other tests. This ensures no leaking or sharing of contexts. Simply pass BDTest your context type as a generic argument using one of the options below.

Automatic Context Construction

(TestContext below is an example class. You pass in the type of your specific context object to these generic classes/methods.)

For either of these methods, your TestContext should have a public constructor with 0 parameters. Otherwise, check out the source code for NUnitBDTestBase to set up your own automatic context injector with extra construction logic.

NUnit

Instead of extending from BDTestBase extend from NUnitBDTestBase<> and pass the type of your Context. Your context will be constructed for each test independently.

Access this using the Context property. See below for example.

This also does some NUnit additional set up, such as registering exception exclusions such as NUnit.SuccessException

This class requires an extra Nuget package (As I didn't want base BDTest to have a dependency on NUnit) Install via Nuget > Install-Package BDTest.NUnit

    public class TestsUsingNUnitBaseWithContext : NUnitBDTestBase<TestContext>
    {
        [Test]
        public void Test1()
        {
            Given(() => Action1(Context))
                .When(() => Action2(Context))
                .Then(() => Action3(Context))
                .BDTest();
        }
    }

Lambda Syntax

Construction of your TestContext using lambda syntax

public class MyTests : BDTestBase
{
    [Test]
    public void Test1() {
        WithContext<TestContext>(context =>
            Given(() => Action1(context))
            .When(() => Action2(context))
            .Then(() => Action3(context))
            .BDTest()
        );
    }
}
  • Your TestContext will be automatically constructed and injected in via the lambda

Thread Safety Parallelization

In order to keep all tests thread safe and have the ability to run all in parallel:

  • Use the NUnitBDTestBase<TestContext> base class OR WithContext<TestContext>(...) syntax as above
  • Do not use static variables/fields/properties in your tests - Store any state in your TestContext object.
  • Do not share fields/properties in your test class - Store any state in your TestContext object - Which the Context construction will take care of
Clone this wiki locally