Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/e51433df9f511956996732f6f5461fcb to your computer and use it in GitHub Desktop.
Save yetanotherchris/e51433df9f511956996732f6f5461fcb to your computer and use it in GitHub Desktop.
Replace type in ServiceCollection for testing
public static class ServiceExtensions
{
public static ServiceCollection ReplaceWithFake<T>(this ServiceCollection services) where T : class
{
T fake = Substitute.For<T>();
var descriptor = new ServiceDescriptor(typeof(T), fake.GetType(), ServiceLifetime.Scoped);
services.Replace(descriptor);
return services;
}
}
// Usage: (install NSubstitute from Nuget)
//services.ReplaceWithFake<ILogger>()
// .ReplaceWithFake<IRepository>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment