'Is there a way create a service object of an NUnit test class to use dependency injection when connecting it to a console app?
I have an NUnit3 project and a console app project in .NET 5 and would like to be able to use dependency injection for a class in my NUnit project. In the console app I am creating the HostBuilder to configure the services for the dependency injection, but in the Main method when I am trying to get the service object of my test class it is returning null. I am not too familiar with DI other than a couple small ASP.NET projects I've done so I don't know if I am doing this right exactly or if this is something that can be done. Any help would be greatly appreciated.
namespace SeleniumTest
{
public interface IDriverHelper
{
public AndroidDriver<AndroidElement> Driver { get; }
}
}
namespace SeleniumTest
{
public class DriverHelper : IDriverHelper
{
private AndroidDriver<AndroidElement> driver;
private AppiumLocalService appiumLocalService;
private AppiumOptions appiumOptions;
public AndroidDriver<AndroidElement> Driver
{
get => driver;
set
{
appiumLocalService = new AppiumServiceBuilder().UsingAnyFreePort().Build();
appiumLocalService.Start();
appiumOptions = new AppiumOptions();
// options added here
driver = new AndroidDriver<AndroidElement>(appiumLocalService, appiumOptions);
}
}
}
}
Here is the beginning of the Test Class
namespace SeleniumTest
{
[TestFixture]
public class Tests
{
private readonly IDriverHelper _driverHelper;
public MyMerlin(IDriverHelper driverHelper)
{
_driverHelper = driverHelper;
}
In the code below, var test = host.Services.GetService<Tests>(); returns null so I am unable to run any of the tests in that class, ex: test.PreSetupTest();
public class Program
{
static Task Main(string[] args)
{
Console.WriteLine("Hello World!");
using IHost host = CreateHostBuilder(args).Build();
var test = host.Services.GetService<Tests>();
test.PreSetupTest();
return host.RunAsync();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
services.AddSingleton<IDriverHelper, DriverHelper>());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
