Given, When, Then

SpecsFor follows the Given, When, Then pattern of specifying tests. You establish context or state in the Given phase, perform an action on the System Under Test in the When phase, then verify the state of things in the Then phase.

public class given_a_car_is_started_when_a_car_is_stopped : SpecsFor<Car>
        {
            protected override void Given()
            {
                //Given: establish state, in this case, that the car is started.
                SUT.Start();
            }

            protected override void When()
            {
                //When: perform an action, in this case, stopping the car.
                SUT.Stop();
            }

            //Note that there can be (and usually are) multiple 'Then' test cases.
            [Test]
            public void then_the_car_is_stopped()
            {
                //Then: the car is stopped.
                SUT.IsStopped.ShouldBeTrue();
            }

            [Test]
            public void then_the_engine_is_stopped()
            {
                //Then: the engine is stopped.
                SUT.Engine.IsStopped.ShouldBeTrue();
            }
        }

Note that both the Given and When methods are optional. You do not have to override them if you do not want to. There may be times where you do not need to establish context first, in which case the Given is not needed. There may also be times where encapsulating the action you are performing in the When method will actually slow things down. In such cases, you can simply add test cases (Then methods) to your spec without specifying a Given or When method.


Did this page help you?