Skip to content

Step Text Attribute

Tom Longhurst edited this page May 2, 2020 · 4 revisions

The [StepText] attribute is designed for outputting a human readable description of what a step is doing.

Annotate your steps/methods with a [StepText] attribute and write a description of that step

[StepText("I perform my second action")]
public void Action2()
{
    ...
}

Step Text (with parameters)

Use parameter indexes to substitute in your arguments to the steptext

[StepText("my name is {0} {1}")]
public void SetName(string firstName, string lastName)
{
    ...
}

public void TestSetName() 
{
    Given(() => SetName("Tom", "Longhurst")) // StepText should equal "Given my name is Tom Longhurst"
    .When(() => SetName("Tom", "Longhurst")) // StepText should equal "When my name is Tom Longhurst"
    .Then(() => SetName("Tom", "Longhurst")) // StepText should equal "Then my name is Tom Longhurst"
    .And(() => SetName("Tom", "Longhurst")) // StepText should equal "And my name is Tom Longhurst"
}

Overriding Step Text

Sometimes, you can't generate a nice step text from attributes due to compile-time constant restraints, or you might have a method that takes a Func<> and won't implicitly convert to a nice readable string.

The way around this would be to add a .WithStepText(() => "text") call to your step.

For instance, I have a method which takes a Func, and it's used to update fields on an API Request Model. I did this so that I don't have to create lots of different methods doing a similar thing. The trade off here was that I can't have a StepText that specifically outlined what I was doing for each test.

So I can override this to a different value for each test, and provide a better context to what action I am performing. This looks like:

.When(() => MyUpdateSteps.UpdateTheField(request => nameof(request.EmailAddress), newEmailAddress)).WithStepText(() => $"I call update customer with a new email address of '{newEmailAddress}'")

Custom Model Converters

If using Step Text (with parameters), we might want custom logic to turn our model into a string. For instance, we might receive a Person object.

First we'd create a class implenting the interface IStepTextStringConverter<Person> We create our logic in the method ConvertToString(Person t)

Then we add this class to the BDTestSettings

BDTestSettings.CustomStringConverters.Add(new PersonStringConverter ());

    public class PersonStringConverter : IStepTextStringConverter<Person>
    {
        public string ConvertToString(Person t)
        {
            return $"First Name: {t.FirstName}\nLast Name: {t.LastName}";
        }
    }
Clone this wiki locally