Skip to content

Commit

Permalink
refactor: Rename TestServiceProvider to BunitServiceProvider (#1416)
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet authored Mar 10, 2024
1 parent 61b6b14 commit 3c9e8b7
Show file tree
Hide file tree
Showing 13 changed files with 47 additions and 44 deletions.
3 changes: 3 additions & 0 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,6 @@ public class HelloWorldInstancePerTestCase : Bunit.TestContext
```

Or use the `BunitContext` directly and manage the lifecycle yourself.

## `TestServiceProvider` renamed to `BunitTestServiceProvider`
The `TestServiceProvider` class has been renamed to `BunitTestServiceProvider`. If you used `TestServiceProvider`, you should replace it with `BunitTestServiceProvider`.
2 changes: 1 addition & 1 deletion docs/samples/tests/xunit/MockHttpClientBunitHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Bunit.Docs.Samples;

public static class MockHttpClientBunitHelpers
{
public static MockHttpMessageHandler AddMockHttpClient(this TestServiceProvider services)
public static MockHttpMessageHandler AddMockHttpClient(this BunitServiceProvider services)
{
var mockHttpHandler = new MockHttpMessageHandler();
var httpClient = mockHttpHandler.ToHttpClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ The highlighted line shows how the `IWeatherForecastService` is registered in th

## Fallback service provider

A fallback service provider can be registered with the built-in `TestServiceProvider`. This enables a few interesting use cases, such as using an alternative IoC container (which should implement the `IServiceProvider` interface), or automatically creating mock services for your Blazor components. The latter can be achieved by using a combination of [AutoFixture](https://github.com/AutoFixture/AutoFixture) and your favorite mocking framework, e.g. Moq, NSubsitute, or Telerik JustMock.
A fallback service provider can be registered with the built-in `BunitServiceProvider`. This enables a few interesting use cases, such as using an alternative IoC container (which should implement the `IServiceProvider` interface), or automatically creating mock services for your Blazor components. The latter can be achieved by using a combination of [AutoFixture](https://github.com/AutoFixture/AutoFixture) and your favorite mocking framework, e.g. Moq, NSubsitute, or Telerik JustMock.

### When is the fallback service provider used?

The logic inside the `TestServiceProvider` for using the fallback service provider is as follows:
The logic inside the `BunitServiceProvider` for using the fallback service provider is as follows:

1. Try resolving the requested service from the standard service provider in bUnit.
2. If that fails, try resolving from a fallback service provider, if one exists.
Expand All @@ -52,7 +52,7 @@ Here is a test where the fallback service provider is used:
In this example, the `DummyService` is provided by the fallback service provider, since it is not registered in the default service provider.

## Using a custom IServiceProvider implementation
A custom service provider factory can be registered with the built-in `TestServiceProvider`. It is used to create the underlying IServiceProvider. This enables a few interesting use cases, such as using an alternative IoC container (which should implement the `IServiceProvider` interface). This approach can be useful if the fallback service provider is not an option. For example, if you have dependencies in the fallback container, that rely on dependencies which are in the main container and vice versa.
A custom service provider factory can be registered with the built-in `BunitServiceProvider`. It is used to create the underlying IServiceProvider. This enables a few interesting use cases, such as using an alternative IoC container (which should implement the `IServiceProvider` interface). This approach can be useful if the fallback service provider is not an option. For example, if you have dependencies in the fallback container, that rely on dependencies which are in the main container and vice versa.

### Registering Autofac service provider factory
The example makes use of `AutofacServiceProviderFactory` and `AutofacServiceProvider` from the package `Autofac.Extensions.DependencyInjection` and shows how to use an Autofac dependency container with bUnit.
Expand Down
2 changes: 1 addition & 1 deletion src/bunit/Asserting/MarkupMatchesAssertExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ public static void MarkupMatches(this RenderedFragment actual, RenderFragment ex
// TODO: This will be obsolete with: https://github.com/bUnit-dev/bUnit/issues/1018
// As the renderer would be transient we don't have to new up an instance
using var renderer = new BunitRenderer(
actual.Services.GetRequiredService<TestServiceProvider>(),
actual.Services.GetRequiredService<BunitServiceProvider>(),
actual.Services.GetRequiredService<ILoggerFactory>());
var renderedFragment = renderer.RenderFragment(expected);
MarkupMatches(actual, renderedFragment, userMessage);
Expand Down
4 changes: 2 additions & 2 deletions src/bunit/BunitContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public partial class BunitContext : IDisposable, IAsyncDisposable
/// Gets the service collection and service provider that is used when a
/// component is rendered by the test context.
/// </summary>
public TestServiceProvider Services { get; }
public BunitServiceProvider Services { get; }

/// <summary>
/// Gets the <see cref="RootRenderTree"/> that all components rendered with the
Expand All @@ -58,7 +58,7 @@ public partial class BunitContext : IDisposable, IAsyncDisposable
/// </summary>
public BunitContext()
{
Services = new TestServiceProvider();
Services = new BunitServiceProvider();
Services.AddSingleton<ComponentFactoryCollection>(_ => ComponentFactories);
Services.AddDefaultBunitContextServices(this, JSInterop);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Bunit;
/// Represents a <see cref="IServiceProvider"/> and <see cref="IServiceCollection"/>
/// as a single type used for test purposes.
/// </summary>
public sealed class TestServiceProvider : IKeyedServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable
public sealed class BunitServiceProvider : IKeyedServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable
{
private static readonly ServiceProviderOptions DefaultServiceProviderOptions = new() { ValidateScopes = true };
private readonly IServiceCollection serviceCollection;
Expand All @@ -18,7 +18,7 @@ public sealed class TestServiceProvider : IKeyedServiceProvider, IServiceCollect
private Func<IServiceProvider> serviceProviderFactory;

/// <summary>
/// Gets a value indicating whether this <see cref="TestServiceProvider"/> has been initialized, and
/// Gets a value indicating whether this <see cref="BunitServiceProvider"/> has been initialized, and
/// no longer will accept calls to the <c>AddService</c>'s methods.
/// </summary>
public bool IsProviderInitialized => serviceProvider is not null;
Expand Down Expand Up @@ -50,15 +50,15 @@ public ServiceProviderOptions Options
}

/// <summary>
/// Initializes a new instance of the <see cref="TestServiceProvider"/> class
/// Initializes a new instance of the <see cref="BunitServiceProvider"/> class
/// and sets its service collection to the provided <paramref name="initialServiceCollection"/>, if any.
/// </summary>
public TestServiceProvider(IServiceCollection? initialServiceCollection = null)
public BunitServiceProvider(IServiceCollection? initialServiceCollection = null)
: this(initialServiceCollection ?? new ServiceCollection(), initializeProvider: false)
{
}

private TestServiceProvider(IServiceCollection initialServiceCollection, bool initializeProvider)
private BunitServiceProvider(IServiceCollection initialServiceCollection, bool initializeProvider)
{
serviceCollection = initialServiceCollection;
serviceProviderFactory = () => serviceCollection.BuildServiceProvider(Options);
Expand Down Expand Up @@ -110,7 +110,7 @@ private void InitializeProvider()
{
CheckInitializedAndThrow();

serviceCollection.AddSingleton<TestServiceProvider>(this);
serviceCollection.AddSingleton<BunitServiceProvider>(this);
rootServiceProvider = serviceProviderFactory.Invoke();
serviceScope = rootServiceProvider.CreateScope();
serviceProvider = serviceScope.ServiceProvider;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Bunit.Extensions;
/// <summary>
/// Helper methods for correctly registering test dependencies.
/// </summary>
public static class TestServiceProviderExtensions
public static class BunitServiceProviderExtensions
{
/// <summary>
/// Registers the default services required by the web <see cref="BunitContext"/>.
Expand Down
6 changes: 3 additions & 3 deletions src/bunit/Rendering/BunitRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Bunit.Rendering;
/// </summary>
public sealed class BunitRenderer : Renderer
{
private readonly TestServiceProvider services;
private readonly BunitServiceProvider services;

[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")]
private static extern ref bool GetIsBatchInProgressField(Renderer renderer);
Expand Down Expand Up @@ -57,7 +57,7 @@ private bool IsBatchInProgress
/// <summary>
/// Initializes a new instance of the <see cref="BunitRenderer"/> class.
/// </summary>
public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory)
public BunitRenderer(BunitServiceProvider services, ILoggerFactory loggerFactory)
: base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService<ComponentFactoryCollection>(), null))
{
this.services = services;
Expand All @@ -68,7 +68,7 @@ public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory)
/// <summary>
/// Initializes a new instance of the <see cref="BunitRenderer"/> class.
/// </summary>
public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator)
public BunitRenderer(BunitServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator)
: base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService<ComponentFactoryCollection>(), componentActivator))
{
this.services = services;
Expand Down
2 changes: 1 addition & 1 deletion src/bunit/Rendering/RenderedFragment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Bunit;
[DebuggerDisplay("Rendered:{RenderCount}")]
public class RenderedFragment : IDisposable
{
[SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by TestServiceProvider, disposed by it.")]
[SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by BunitServiceProvider, disposed by it.")]
private readonly BunitHtmlParser htmlParser;
private string markup = string.Empty;
private INodeList? latestRenderNodes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class BunitAuthorizationContext
/// <summary>
/// Creates a new instance of <see cref="BunitAuthorizationContext"/>.
/// </summary>
internal BunitAuthorizationContext(TestServiceProvider services)
internal BunitAuthorizationContext(BunitServiceProvider services)
{
services.AddSingleton<IAuthorizationService>(authService);
services.AddSingleton<IAuthorizationPolicyProvider>(policyProvider);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace Bunit;
public partial class BunitContext
{
/// <summary>
/// Adds the appropriate Blazor authentication and authorization services to the <see cref="TestServiceProvider"/> to enable
/// Adds the appropriate Blazor authentication and authorization services to the <see cref="BunitServiceProvider"/> to enable
/// an authenticated user, as well as adding the <see cref="CascadingAuthenticationState"/> component to the
/// test contexts render tree.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal BunitPersistentComponentState(IServiceProvider services)
/// <remarks>
/// Only call this method after all services has been registered with the <see cref="BunitContext.Services"/>.
/// Calling this method will lookup dependencies of the <see cref="BunitPersistentComponentState"/>
/// from the <see cref="TestServiceProvider"/>, which means no other services can be registered after this point.
/// from the <see cref="BunitServiceProvider"/>, which means no other services can be registered after this point.
/// </remarks>
public void TriggerOnPersisting()
{
Expand All @@ -52,7 +52,7 @@ public void TriggerOnPersisting()
/// <remarks>
/// Only call this method after all services has been registered with the <see cref="BunitContext.Services"/>.
/// Calling this method will lookup dependencies of the <see cref="BunitPersistentComponentState"/>
/// from the <see cref="TestServiceProvider"/>, which means no other services can be registered after this point.
/// from the <see cref="BunitServiceProvider"/>, which means no other services can be registered after this point.
/// </remarks>
/// <typeparam name="TValue">The <paramref name="instance"/> type.</typeparam>
/// <param name="key">The key to use to persist the state.</param>
Expand All @@ -72,7 +72,7 @@ public void Persist<TValue>(string key, TValue instance)
/// <remarks>
/// Only call this method after all services has been registered with the <see cref="BunitContext.Services"/>.
/// Calling this method will lookup dependencies of the <see cref="BunitPersistentComponentState"/>
/// from the <see cref="TestServiceProvider"/>, which means no other services can be registered after this point.
/// from the <see cref="BunitServiceProvider"/>, which means no other services can be registered after this point.
/// </remarks>
/// <param name="key">The key used to persist the instance.</param>
/// <param name="instance">The persisted instance.</param>
Expand Down
Loading

0 comments on commit 3c9e8b7

Please sign in to comment.