21

I am just getting into the concept of BDD and have listened to Scott Bellware's talk with the Herding Code guys. I have been playing around with SpecFlow some and like it pretty well.

I understand the distinction between ATDD and TDD as described in the blog post Classifying BDD Tools (Unit-Test-Driven vs. Acceptance Test Driven) and a bit of BDD history, but that leads me to a question.

As described, isn't using a BDD tool (such as MSpec) just another unit testing framework? It seems to me that it is.

Furthermore, this seems to suggest that using SpecFlow to spec out the lower level components (such as your repositories and services) would be wrong. If I can use the same tool for both ATDD and TDD of lower level components, why shouldn't I? There seems to still be some blurry lines here that I feel like I'm not quite understanding.

Brian McCord
  • 4,863
  • 6
  • 28
  • 44

5 Answers5

29

The Quick Answer

One very important point to bring up is that there are two flavors of Behavior Driven Development. The two flavors are xBehave and xSpec.

xBehave BDD: SpecFlow

SpecFlow (very similar to cucumber from the Ruby stack) is excellent in facilitating xBehave BDD tests as Acceptance Criteria. It does not however provide a good way to write behavioral tests on a unit level. There are a few other xBehave testing frameworks, but SpecFlow has gotten a lot of traction.

xSpec BDD: NSpec

For behavior driven development on a unit level, I would recommend NSpec (inspired directly by RSpec for Ruby). You can accomplish BDD on a unit level by simply using NUnit or MSTest...but they kinda fall short (it's really hard to build up contexts incrementally). MSpec is also an option, there has been a lot of work put into it, but there are just somethings that are just simpilier in NSpec (you can build up context incrementally in MSpec, but it requires inheritance which can become complex).

The Long Answer

The two flavors of BDD primarily exist because of the orthogonal benefits they provide.

Pros and Cons of xBehave (GWT Syntax)

Pros

  • helps facilitate a conversations with the business through a common dialect called (eg. Given ...., And Given ...., When ......, And When ..... , Then ...., And Then)
  • the common dialect can then be mapped to executable code which proves to the business that you actually finished what you said you'd finish
  • the dialect is constricting, so the business has to disambiguate requirements and make it fit into the sentences.

Cons

  • While the xBehave approach is good for driving high level Acceptance Criteria, the cycles needed to map English to executable code via attributes makes it infeasible for driving out a domain at the unit level.
  • Mapping the common dialect to tests is PAINFUL (ramp up on your regex). Each sentence the business creates must be mapped to an executable method via attributes.
  • The common dialect must be tightly controlled so that managing the mapping doesn't get out of hand. Any time you change a sentence, you have to find method that directly relates to that sentence and fix the regex matching.

Pros and Cons of xSpec (Context/Specification)

Pros

  • Allows the developer to build up context incrementally. A context can be set up for a test and some assertions can be performed against that context. You can then specify more context (building upon the context that already exists) and then specify more tests.
  • No constricting language. Developers can be more expressive about how a certain part of a system behaves.
  • No mapping needed between English and a common dialect (because there isn't one).

Cons

  • Not as approachable by the business. Let's face it, the business don't like to disambiguate what they want. If we gave them a context based approach to BDD then the sentence would just read "Just make it work".
  • Everything is in the code. The context documentation is intertwined within the code (that's why we don't have to worry about mapping english to code)
  • Not as readable given a less restrictive verbiage.

Samples

The Bowling Kata is a pretty good example.

SpecFlow Sample

Here is what the specification would look like in SpecFlow (again, this is great as an acceptance test, because it communicates directly with the business):

Feature File

The feature file is the common dialect for the test.

Feature: Score Calculation 
  In order to know my performance
  As a player
  I want the system to calculate my total score

Scenario: Gutter game
  Given a new bowling game
  When all of my balls are landing in the gutter
  Then my total score should be 0
Step Definition File

The step definition file is the actual execution of the test, this file includes the mappings for SpecFlow


[Binding]
public class BowlingSteps
{
    private Game _game;

    [Given(@"a new bowling game")]
    public void GivenANewBowlingGame()
    {
        _game = new Game();
    }

    [When(@"all of my balls are landing in the gutter")]
    public void WhenAllOfMyBallsAreLandingInTheGutter()
    {
        _game.Frames = "00000000000000000000";
    }

    [Then(@"my total score should be (\d+)")]
    public void ThenMyTotalScoreShouldBe(int score)
    {
        Assert.AreEqual(0, _game.Score);
    }
}

NSpec Sample, xSpec, Context/Specification

Here is a NSpec example of the same bowling kata:


class describe_BowlingGame : nspec
{
    Game game;

    void before_each()
    {
        game = new Game();
    }

    void when_all_my_balls_land_in_the_gutter()
    {
        before = () =>
        {
            game.Frames = "00000000000000000000";
        };

        it["should have a score of 0"] = () => game.Score.should_be(0);
    }
}

So Yea...SpecFlow is cool, NSpec is cool

As you do more and more BDD, you'll find that both the xBehave and xSpec flavors of BDD are needed. xBehave is more suited for Acceptance Tests, xSpec is more suited for unit tests and domain driven design.

Relevant Links

Community
  • 1
  • 1
Amir
  • 8,861
  • 5
  • 32
  • 46
11

A true behavior driven tool would be something like Cucumber. We use it at my job against .NET code. This allows us to write features that define behavior of the system as a whole and we can then execute the features and verify that the system does what we expect. The whole process works very well for us.

http://cukes.info/

There is a .net implementation called NStep that connects to cucumber via the wire protocol, it allows you to write step definitions in C# using lambdas...its pretty awesome.

Step definitions look like this:

When("^I go to the \"([^\"]*)\" (?:[Ss]creen|[Pp]age)$", (string pageName) =>
{
    var screen = ParseScreen(pageName);
    GoToScreen(screen);
    World.Browser.Wait(1000);
});

http://github.com/clearwavebuild/nStep

Chris Kooken
  • 29,979
  • 14
  • 79
  • 113
  • 1
    SpecFlow is a .NET implementation of Cucumber. – Brian McCord Jul 29 '10 at 03:44
  • Except it is a clone, with its own parser and it compiles the steps into unit tests. No matter how good, a clone will never be as good as the original. Cucumber is constantly adding features that makes the BDD approach a great way to write software. You should check out actual cucumber...it's pretty powerful. – Chris Kooken Jul 29 '10 at 03:48
  • BDD tools are really designed to test behavior. So it should encompass the system as a whole. For the underlying core business processes like repositories I would use NUnit and use SpecFlow or Cucumber for Behavior Testing. – Chris Kooken Jul 29 '10 at 03:52
  • This is why I love SO, learn something new every day. SpecFlow and cucumber look pretty cool. – Nathan W Jul 29 '10 at 03:53
  • 3
    +1 for nstep and not reinventing the wheel. NStep implements the cucumber wire protocol so that you can implement steps in .NET while using the ruby cucumber runner. SpecFlow is fine and dandy, but you miss out on all of the tooling out there for cucumber. You also lack the ability to mix simple and dynamic ruby code (great for working with APIs like Selenium) and .NET code (great for working with databases and service facades). – Joseph Daigle Jul 29 '10 at 13:49
  • 2
    Current versions of SpecFlow are using the official Gherkin parser that is also used in Cucumber. On the tooling side SpecFlow is tring to provide a good experience for standard .NET development setups. The VisualStudio integration is constantly improving and using existing test-automation frameworks (NUnit, MSTest ...) for execution is a explicit decision to make integration into existing infrastructure painless. We try hard not to reinvent the wheel... – jbandi Apr 07 '11 at 06:24
2

I think your understanding is in line with mine. BDD is more suited for integration testing and generally tests your system as the end user, eg:

Given I am an authorised user
When I go to the front page
Then there should be a link to my profile with my username as the link text.

There is no reason to not to unit test your repositories at a more granular level. I think both are useful and appropriate.

Igor Zevaka
  • 69,206
  • 26
  • 104
  • 125
  • I still test my repositories, services, etc. (with NUnit currently), but what I'm really wondering is if it is considered "wrong" to use SpecFlow for this purpose also. – Brian McCord Jul 29 '10 at 03:46
  • 2
    I would think so, SpecFlow is more suited to testing large chunks of code as is, with no mocking or isolating. – Igor Zevaka Jul 29 '10 at 03:54
  • I agree with Igor because the real advantage of using BDD tools is that it allows business users to write the tests (or alternatively, it allows the business users to understand the tests). Since business only really cares about the system as a whole, BDD tools are suited to testing the system as a whole. The business does not really care whether the repository works if it cannot integrate with the system as a whole. So for more unit level testing, BDD will more likely get in the way rather than help. – Trumpi Apr 13 '11 at 14:32
2

Can't I just use normal unit testing tools? BDD is a process and mentality and so, yes, you can do it with any tools (or not, you can write your own without a tool if you want). However, the TDD tools had certain assumptions which cause some friction when trying to do things in a BDD way. For instance, TDD assumes you are testing an architectural unit of the software; class, module, service. Whereas BDD assumes you are specifying some functional portion of the system.

Should I use SpecFlow/Cucumber to describe lower-level components? First of all, I think the question is a bit misguided. You wouldn't tend to describe components unless those components directly represent behavior. I'll still answer what I believe the spirit of the question is.

Story oriented tools like Cucumber are great for talking about behavior from a customer/user perspective. It can allow you to make specifications that are easily approachable by laymen. However, it can be tedious to describe large amounts or complex state with those tools.

Unit testing, or more code oriented specification tools like rSpec and Machine.Specification, can be a lot more convenient when dealing with complex or large state setups. You can use the various tools available to the languages to manage the state. Things like inheritance and fakes/mocks. Machine.Specification has some good approaches to this for the .NET minded.

So, should you use Cucumber to specify lower-level behavior? I'd say only if its important to have high levels of visibility for that particular behavior. On my current project, we've developed an architectural component to represent certain business-rule intensive portions of the system. Those components are specified with Cucumber, but the majority of system is covered with NUnit.


Btw, SpecFlow is really nice and approachable for .NET folks just getting into BDD, but eventually you'll want to graduate to full-blown Cucumber+nStep. The Cucumber ecosystem is HUGE and helpful. SpecFlow's is much smaller.

Also, the lambda syntax offered by nStep is quite a bit nicer than having to decorate methods a la SpecFlow or Cuke4Nuke.

Disclaimer/Background: I did some of the original development on nStep but I'm using SpecFlow on my current project. I'm working to introduce BDD here and needed something simple and approachable.

brendanjerwin
  • 1,371
  • 2
  • 11
  • 24
0

It is interesting that this blog on Classifying BDD Tools talks about TDD and ATDD. As Liz Keogh points out: BDD is about conversation and exploration. The easier it is for all involved guys to contribute, communicate intension, share ideas, understand the others, etc. the faster we get to an adequate solution and the better software we build. When we finally follow the tool path, what are the tools that support collaboration between stakeholders of software projects best?

Based on the this blog on the differences between TDD, BDD, and ATDD I would say that there are at least three different flavors of BDD tool:

  1. Unit Testing Frameworks

JUnit changed our view on development and testing. One of its strengths is that tests can be written in the same programming language as the application itself. Thus, we can build on the knowledge we already have in the delivery team. When the tests are even used to drive the development we reach the heaven of TDD.

Programming languages have been optimized to reduce redundancy, which is according to Ron Jeffries one of the worst sins of developers. Therefore, we often rely on these tools when we do technical testing to build the product right as they help us to be most efficient.

Several guys tried to make automated tests more understandable, as unit tests aren't really readable. One of the first attempts was to parse unit tests and provide a concise summary that is also readable to non-developers. For example TestDox / AgileDox creates simple documentation from the method names of JUnit test classes or Pickels generates documentation based on feature files written in Gherkin.

Frameworks such as MSpec help to write tests that are better readable and additionally provide readable output. These flavor of BDD tools focuses on human readable output, which enables the involvement of non-developers after the developers did their job.

  1. Scenario Testing Frameworks

To involve stakeholders earlier in the development cycle, new tools were created that focus more on readable input. Cucumber utilizes plain text files to provide human readable inputs for automated tests. The text files contain scenarios written in a specially structured language based on the given-when-then structure. These frameworks are great tools that support collaborative definition of acceptance criteria.

  1. Acceptance Testing Frameworks

In parallel to the BDD idea, another flavor of tools has been developed, where FIT was an early representative. This Framework for Integrated Test allows to specify examples within tables that are embedded into a documentation related to the examples. To write these documents no development skills are required and they can be easily read and reviewed by non technical guys as they are purely text based. Additionally, the text can be structured as the documents are not plain text files but the output of rich editors.

FitNesse allows to specify the expected behavior collaboratively based on a wiki. As wikis are easy to access and use, it has a low entry and learning curve, which propels the common work of the entire team. Many agile proponents emphasize that the best way for collaboration is face-to-face communication. But, if you write down what you have thought and discussed, it should be as rich and well structured as possible.

Concordion provides a lot of flexibility as you can describe your requirements in normal language using paragraphs, tables and proper punctuation. Any part of your description can be used as input to your automated tests and for the validation of the outputs of your system under test. As it is based on HTML you can structure your documents and integrate images. Simply, you have the expressiveness of the web to describe the expected behavior.

BDD should help to build the right product

You could implement BDD with all three flavors of tools, but each has its strengths and weaknesses. Unit testing frameworks and xSpec like tools perfectly use the strengths of programming. As they are tools from developers for developers, they are a perfect choice if you try to get the technical part right.

When you want to communicate the intention of the application you are probably better off with a tool that is strongly related with tools that editors use for their work. If a specification contains only inputs and expected outputs, anyone who reads it will have to reconstruct your ideas from the relation of inputs to expected outputs. A short description explaining the goal of a specification in the header helps the reader understand the structure of the specification. Documents based on specification-by-example could look like:

enter image description here enter image description here

Yes, SpecFlow is cool, NSpec is cool ...

FitNesse and Concordion are cool as well

Community
  • 1
  • 1
user3632158
  • 267
  • 1
  • 6