C
C#•4mo ago
StilauGamer

xUnit and Dependency Injection

Hello, I have not ran too many unit testings up through my time, but recently getting into a bit more of a heavy program where unit testing will be crucial. The project is dependent on Dependency Injection, and I was wondering if its possible to run unit tests on methods from DI services...? I have currently a Core Project and a Test Project, and I want to be able to get a DI service from the Core Project and run a test with it inside the test project. How would I be able to do this? Any help is appreciated, Thanks 😊
3 Replies
FusedQyou
FusedQyou•4mo ago
Sure, just make your own ServiceCollection, make sure to add the required dependencies the same way as in the Core Project, and then run tests with them It's pretty normal. If you have dependencies you don't necessarily need you could also mock them
Unknown User
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View
becquerel
becquerel•4mo ago
my preferred way of doing this is to define an extension method which is shared between my 'real' app and the test code. e.g.
// ServiceCollectionExtensions.cs
public static class ServiceCollectionExtensions
{
public static void AddFoobarServices(this IServiceCollection services)
{
// Pretend we add a dozen other services here if you want.
services.AddSingleton<MyFoobarCreator>();
}
}

// Program.cs
var builder = HostBuilder.CreateDefaultBuilder();
builder.Services.AddFoobarServices();
await builder.Build().RunAsync();

// MyTestClass.cs
public class MyTestClass
{
private readonly MyFoobarCreator _sut;

public MyTestClass()
{
var services = new ServiceCollection();
services.AddFoobarServices();
var provider = services.BuildServiceProvider();
_sut = provider.GetRequiredService<MyFoobarCreator>();
}

[Fact]
public void TestFoobars() => _sut.Whatever();
}
// ServiceCollectionExtensions.cs
public static class ServiceCollectionExtensions
{
public static void AddFoobarServices(this IServiceCollection services)
{
// Pretend we add a dozen other services here if you want.
services.AddSingleton<MyFoobarCreator>();
}
}

// Program.cs
var builder = HostBuilder.CreateDefaultBuilder();
builder.Services.AddFoobarServices();
await builder.Build().RunAsync();

// MyTestClass.cs
public class MyTestClass
{
private readonly MyFoobarCreator _sut;

public MyTestClass()
{
var services = new ServiceCollection();
services.AddFoobarServices();
var provider = services.BuildServiceProvider();
_sut = provider.GetRequiredService<MyFoobarCreator>();
}

[Fact]
public void TestFoobars() => _sut.Whatever();
}
this way you keep the tests in sync with the real app with a lot less effort + it reads more cleanly

Did you find this page helpful?