-
Notifications
You must be signed in to change notification settings - Fork 5
Steps Classes
Tom Longhurst edited this page Apr 27, 2020
·
3 revisions
Steps can be organised into relevant classes, which take your TestContext
object in their constructor. This allows your steps to manipulate your context for that test. For example, you might store a HttpRequest
and a HttpResponse
, a step might execute that request. You want to then store the HttpResponse
in that context, so that you can assert on it later.
An example steps class, complete with StepText
attribute:
public class AccountSteps
{
private readonly MyTestContext _context;
public AccountSteps(MyTestContext context)
{
_context = context;
}
[StepText("I create a new account")]
public async Task CreateAnAccount()
{
await _context.ApiContext.ExecuteRequest(new HttpRequestMessage
{
RequestUri = new Uri("https://www.example.com/endpoints/create"),
Method = HttpMethod.Post,
Content = new JsonContent<dynamic>(new
{
FirstName = "Tom",
LastName = "Longhurst"
})
});
}
}
Steps should be defined as properties, and new'd up in the getter. This means that any test that calls them, the steps class has the correct context.
If these were defined as fields, every test would be sharing the same context. So it is important that these are properties with getters.
public abstract class MyTestBase : NUnitBDTestBase<MyTestContext>
{
// Make sure these steps are properties with getters - Not fields. They should be constructed each time with the relevant context!
public AccountSteps AccountSteps => new AccountSteps(Context);
public AccountAssertions AccountAssertions => new AccountAssertions(Context);
public HttpAssertions HttpAssertions => new HttpAssertions(Context);
}
[Test]
[ScenarioText("Create an account returns OK")]
public async Task CreateAccountSuccessfully()
{
await When(() => AccountSteps.CreateAnAccount())
.Then(() => HttpAssertions.TheHttpStatusCodeIs(HttpStatusCode.OK))
.BDTestAsync();
}