Skip to content

AddAuthorization() / AddTestAuthorization() doesn't work with shallow rendering #1774

@aayjaychan

Description

@aayjaychan

Describe the bug

When testing a component with authentication, using shallow rendering to replace all child components throws ComponentNotFoundException.

Example:
Foo.razor:

@using System.Threading.Tasks;
@using Microsoft.AspNetCore.Components.Authorization

<div>
</div>

@code
{
    [CascadingParameter]
    public Task<AuthenticationState> Auth { get; set; } = null!;
}

Test:

using Bunit;
using NUnit.Framework;

public sealed class FooTests
{
    [Test]
    public void TestFoo()
    {
        using BunitContext testContext = new();

        testContext.AddAuthorization();
        testContext.ComponentFactories
            .AddStub(componentType => componentType != typeof(Foo));
        testContext.Render<Foo>();
    }
}

Results in this output:

Bunit.Rendering.ComponentNotFoundException : A component of type ContainerFragment was not found in the render tree.
   at Bunit.Rendering.BunitRenderer.FindComponent[TComponent](IRenderedComponent`1 parentComponent) in /_/src/bunit/Rendering/BunitRenderer.cs:line 216
   at Bunit.BunitContext.RenderInsideRenderTree(RenderFragment renderFragment) in /_/src/bunit/BunitContext.cs:line 226
   at Bunit.BunitContext.RenderInsideRenderTree[TComponent](RenderFragment renderFragment) in /_/src/bunit/BunitContext.cs:line 208
   at Bunit.BunitContext.Render[TComponent](RenderFragment renderFragment) in /_/src/bunit/BunitContext.cs:line 163
   at Bunit.BunitContext.Render[TComponent](Action`1 parameterBuilder) in /_/src/bunit/BunitContext.cs:line 149
   at FooTests.TestFoo() in /mnt/data/Projects/Tests/FooTests.cs:line 15
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)

Expected behavior:

Services and components added by AddTestAuthorization() are not affected by AddStub().

Version info:

  • bUnit version: 1.40.0, 2.0.64-preview
  • .NET Runtime and Blazor version: 8.0.20

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions