bUnit-dev / bUnit

bUnit is a testing library for Blazor components that make tests look, feel, and runs like regular unit tests. bUnit makes it easy to render and control a component under test’s life-cycle, pass parameter and inject services into it, trigger event handlers, and verify the rendered markup from the component using a built-in semantic HTML comparer.
https://bunit.dev
MIT License
1.14k stars 105 forks source link

Support for keyed services #1373

Closed ViRuSTriNiTy closed 8 months ago

ViRuSTriNiTy commented 8 months ago

Hi there,

.NET 8 comes with a new feature named keyed services.

Currently, when using this feature in a component tested with Bunit the following exception is thrown:

System.InvalidOperationException : Cannot provide a value for property 'Service' on type 'MyComponent'. The service provider does not implement 'IKeyedServiceProvider' and therefore cannot provide keyed services.

It seems like keyed service support is missing.

Example:

public class MyServiceKey
{
}

public class MyService
{
    public MyService()
    {
    }
}

public class MyComponent : ComponentBase
{
    [Inject(Key = typeof(MyServiceKey))]
    public required MyService Service { get; set; }
}

[Fact]
public void Test()
{
    using var testContext = new TestContext();
    testContext.Services.AddKeyedScoped<MyService>(typeof(MyServiceKey));

    var component = testContext.RenderComponent<MyComponent>();
}

Is it planed to support keyed services or should I go the route of a fallback service provider or even replacing the default service provider?

egil commented 8 months ago

Hey @ViRuSTriNiTy, thanks for bringing this to our attention.

That's definitely something we need to add support for. If you are up to it, feel free to add support for this by extending https://github.com/bUnit-dev/bUnit/blob/main/src/bunit.core/TestServiceProvider.cs and send in a PR.

linkdotnet commented 8 months ago

There should be a preview package available in a few moments @ViRuSTriNiTy If you have time and gives us feedback whether or not that fits your needs, that would be great. Preview version should be 1.27.11

ViRuSTriNiTy commented 8 months ago

@linkdotnet Latest preview works like a charm! Thanks a bunch 😎. When will this state be released as official version?

linkdotnet commented 8 months ago

Yes "soon" ™️ 😄

linkdotnet commented 7 months ago

"Soon" arrived - we are preparing a release, so there will be a stable 1.27 coming in the coming minutes.

Edit: Released with version 1.27.17