Skip to content

Defining a custom syntax

Michael W Powell edited this page Dec 8, 2020 · 3 revisions

Extending xWellBehaved.net is very easy. It is itself an extension to xUnit.net and has been built with extensibility in mind.

For example, the default syntax in xBehave.net is [Scenario] and x() but this is easy to change. You can inherit from the [Scenario] attribute to provide your own alternative language for the 'scenario' concept. You can define a custom method) to replace .x(...).

For instance, adding xSpec style [Spec] and .Do(...):

using System;

namespace Widget.Specs
{
    using Xunit;
    using Xwellbehaved;

    // custom syntax
    public class SpecAttribute : ScenarioAttribute
    {
    }

    public static class XSpecExtensions
    {
        public static IStepBuilder Do(this string text, Action body) => text.x(body);
    }

    // specs
    public class DescribeCalculator
    {
        [Spec]
        public void When1And2AreAdded(Calculator calculator, int answer)
        {
            "Establish a calculator".Do(() => calculator = new Calculator());

            "Because I add 1 and 2 together".Do(() => answer = calculator.AssertNotNull().Add(1, 2));

            "It answers 3".Do(() => answer.AssertEqual(3));
        }
    }

    // system under test
    public class Calculator
    {
        public int Add(int x, int y) => x + y;
    }
}

Note that to support object disposal and async steps you need to define overloads of each of your custom step methods as shown in defining a custom step method.

Clone this wiki locally