Dependency Injection
In most of the examples in our Stories we have called our API directly to perform the test arrangement. Sometimes this isn't good enough, we may need to simulate an incoming message on a Message Queue or want to insert some data directly into our API Database.
If this is the case we can tell Bard how to resolve services when we configure the Scenario and access them within the Story through the ScenarioContext. This is particularly easy if you are testing a .NET API.

Dependency Injection Configuration

1
var hostBuilder = new HostBuilder()
2
.ConfigureWebHost(builder =>
3
builder
4
.UseStartup<Startup>()
5
.UseTestServer()
6
.UseEnvironment("development"));
7
​
8
var host = hostBuilder.Start();
9
​
10
var httpClient = host.GetTestClient();
11
​
12
Scenario = ScenarioConfiguration
13
.Configure(options =>
14
{
15
options.Client = httpClient;
16
options.LogMessage = output.WriteLine;
17
options.Services = host.Services;
18
});
Copied!

Using ServiceProvider In A Story

1
public BankAccountHasBeenCreated BankAccount_has_been_created()
2
{
3
return When(context =>
4
{
5
var bankAccountMessage = new BankAccount
6
{
7
CustomerName = "Ranulph Fiennes"
8
};
9
​
10
var serviceBus = context.Services.GetService<IServiceBus>()
11
12
serviceBus.AddMessage(message);
13
14
context.StoryData.BankAccount = bankAccountMessage;
15
16
})
17
.ProceedToChapter<BankAccountHasBeenCreated>();
18
}
Copied!
Last modified 1yr ago