Skip to content
amirci edited this page Mar 7, 2011 · 2 revisions

Given, When, Then is a style of writing scenarios, borrowed from BDD tools like Cucumber.

Here is an example of the usage in Cucumber describing a scenario for a web application that works with movies:

Scenario: List the movies
   Given I have the movies "Blazing Saddles" and "Young Frankenstein"
   When  I go to "list movies" page
   Then  I should see "Blazing Saddles" and "Young Frankenstein" in the listing

When applied to unit tests, if you are familiar with the AAA style (Arrange, Act, Assert) GWT is very similar:

  • Given = Arrange
  • Act = When
  • Assert = Then

Though I like AAA, I wanted a way to enforce how the scenarios should be written, that's why the MT Testing library enforces GWT syntax using the following methods that are called from the base class:

  • Given = GivenThat()
  • When = WhenIRun()
  • Then = Any method with the It attribute or the test attribute used by the chosen framework

Each scenario is written in a separate file, usually with a name that identifies the scenario like When_movie_library_adds_a_movie. The intent of the test is very clear, and the GWT syntax makes very easy to understand the code. Consider the following scenario:

Scenario: Add a movie to the library
   Given I have no movies
   When  I add the movie "Blazing Saddles"
   Then  I should see "Blazing Saddles" in the contents

And translating that to code, we get:

        protected override void GivenThat()
        {
            this.Library.Clear();
        }

        protected override void WhenIRun()
        {
            this.Library.Add("Blazing Saddles");
        }

        [It]
        public void Should_have_the_movie_in_the_contents()
        {
            Assert.IsTrue(this.Library.Contains("Blazing Saddles"));
        }

Clone this wiki locally