Skip to content

Instantly share code, notes, and snippets.

@mowensoft
Last active March 24, 2016 14:32
Show Gist options
  • Save mowensoft/d493b413e6329c5ed50b to your computer and use it in GitHub Desktop.
Save mowensoft/d493b413e6329c5ed50b to your computer and use it in GitHub Desktop.
BDD-style specifications using NUnit
using System;
using NUnit.Framework;
namespace Bdd
{
[TestFixture]
public abstract class Specification
{
protected Exception CaughtException = new ThereWasNoExceptionButOneWasExpectedException();
public virtual void Given()
{
}
public abstract void When();
[SetUp]
public void Init()
{
Given();
try
{
When();
}
catch (Exception exception)
{
CaughtException = exception;
}
}
}
public class ThenAttribute : TestAttribute
{
}
public class ThereWasNoExceptionButOneWasExpectedException : Exception
{
public ThereWasNoExceptionButOneWasExpectedException()
: base("There was no exception but one was expected")
{
}
}
}
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
public class CalculatorTests
{
public class When_adding_two_numbers : Specification
{
protected Calculator Calculator;
protected int Sum;
public override void Given()
{
Calculator = new Calculator();
}
public override void When()
{
Sum = Calculator.Add(2, 3);
}
[Then]
public void It_should_sum_the_numbers_correctly()
{
Assert.That(Sum, Is.EqualTo(5));
}
/// <remarks>
/// Just demonstrating multiple tests per scenario
/// </remarks>
[Then]
public void It_should_be_positive()
{
Assert.That(Sum, Is.GreaterThan(0));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment