From e44c30bfd9af6ad4a2fb96a63a7c44c5bc90e272 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 5 Sep 2026 17:50:12 +0200 Subject: [PATCH 1/7] chore: Bump to v3 --- .github/workflows/ci.yml | 1 + version.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a52b66ad..37b9761d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,7 @@ on: push: branches: - main + - v3 paths: - 'src/**' - 'tests/**' diff --git a/version.json b/version.json index b6ff506b5..a372a9054 100644 --- a/version.json +++ b/version.json @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/main/src/NerdBank.GitVersioning/version.schema.json", - "version": "2.12-preview", + "version": "3.0-alpha", "assemblyVersion": { "precision": "revision" }, From cfa66caf256f8a0a7f6f77c626f2eecd10dd6906 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 5 Sep 2026 18:44:52 +0200 Subject: [PATCH 2/7] fix: Drop old TFM (fixes #1886) --- .github/workflows/ci.yml | 8 +- .github/workflows/docs-deploy.yml | 2 - .github/workflows/release.yml | 2 - Directory.Packages.props | 30 --- .../components/bunit.docs.samples.csproj | 2 +- docs/samples/tests/Directory.Build.props | 2 +- docs/site/docs/extensions/bunit-generators.md | 4 +- .../getting-started/create-test-project.md | 16 +- docs/site/docs/migrations/2to3.md | 18 ++ docs/site/docs/migrations/index.md | 1 + .../docs/providing-input/seeding-assets.md | 2 +- docs/site/docs/toc.md | 1 + src/bunit.generators.internal/README.md | 2 +- src/bunit.generators/README.md | 4 +- .../.template.config/dotnetcli.host.json | 8 +- .../template/.template.config/template.json | 10 - src/bunit.web.query/bunit.web.query.csproj | 2 +- src/bunit/BunitContext.cs | 6 - src/bunit/ComponentParameterCollection.cs | 4 - .../ComponentParameterCollectionBuilder.cs | 2 - .../Implementation/BunitJSObjectReference.cs | 5 - .../Implementation/BunitJSRuntime.net10.cs | 2 - .../Implementation/BunitJSRuntime.net8.cs | 27 --- .../Implementation/JSRuntimeExtensions.cs | 2 - src/bunit/Rendering/BunitHtmlParser.cs | 3 +- src/bunit/Rendering/BunitRenderer.cs | 7 +- src/bunit/Rendering/Internal/Htmlizer.cs | 2 - .../Rendering/MissingRendererInfoException.cs | 2 - .../Rendering/RenderModeMisMatchException.cs | 2 - src/bunit/bunit.csproj | 2 +- .../bunit.generators.tests.csproj | 2 +- tests/bunit.testassets/DumpCapture.cs | 8 - .../RenderModes/RendererInfoComponent.cs | 3 - .../RenderModes/SectionOutletComponent.cs | 7 - .../bunit.testassets/bunit.testassets.csproj | 2 +- .../JSInterop/BunitJSInteropTest.cs | 184 ------------------ .../JSInterop/BunitJsObjectReferenceTest.cs | 120 ------------ ...irtualizeJsRuntimeInvocationHandlerTest.cs | 12 -- .../Rendering/RenderedComponentTest.cs | 2 +- tests/bunit.tests/bunit.tests.csproj | 2 +- .../bunit.web.query.tests.csproj | 2 +- 41 files changed, 52 insertions(+), 472 deletions(-) create mode 100644 docs/site/docs/migrations/2to3.md delete mode 100644 src/bunit/JSInterop/Implementation/BunitJSRuntime.net8.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37b9761d7..cd53d67a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,8 +45,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x @@ -127,8 +125,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x @@ -226,8 +222,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x @@ -257,7 +251,7 @@ jobs: - name: 🧪 Run sample unit tests working-directory: docs/samples - run: dotnet test samples.sln -p:VSTestUseMSBuildOutput=false -f net8.0 + run: dotnet test samples.sln -p:VSTestUseMSBuildOutput=false -f net10.0 - name: 📄 Build docs working-directory: ./docs/site diff --git a/.github/workflows/docs-deploy.yml b/.github/workflows/docs-deploy.yml index 35f3bbdfe..7b9be3aa8 100644 --- a/.github/workflows/docs-deploy.yml +++ b/.github/workflows/docs-deploy.yml @@ -73,8 +73,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c6284e036..72d934d0a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,8 +63,6 @@ jobs: uses: actions/setup-dotnet@v6 with: dotnet-version: | - 8.0.x - 9.0.x 10.0.x 11.0.x diff --git a/Directory.Packages.props b/Directory.Packages.props index 8a23376ef..3d275125a 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -26,36 +26,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/samples/components/bunit.docs.samples.csproj b/docs/samples/components/bunit.docs.samples.csproj index 88949209f..9e1e852d7 100644 --- a/docs/samples/components/bunit.docs.samples.csproj +++ b/docs/samples/components/bunit.docs.samples.csproj @@ -1,7 +1,7 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit.Docs.Samples enable CA1014,NU5104 diff --git a/docs/samples/tests/Directory.Build.props b/docs/samples/tests/Directory.Build.props index 8071ce9d1..9a5722898 100644 --- a/docs/samples/tests/Directory.Build.props +++ b/docs/samples/tests/Directory.Build.props @@ -1,6 +1,6 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 false true false diff --git a/docs/site/docs/extensions/bunit-generators.md b/docs/site/docs/extensions/bunit-generators.md index c9c072908..74d9b3f97 100644 --- a/docs/site/docs/extensions/bunit-generators.md +++ b/docs/site/docs/extensions/bunit-generators.md @@ -53,12 +53,12 @@ To use the generator, the **Interceptor** feature has to be used inside the cspr ```xml - net8.0 + net10.0 $(InterceptorsPreviewNamespaces);Bunit ``` -Due to the usage of **Interceptors** the generator is only available for .NET 8.0 and above. The generator does create a `partial` class, so it can be extended with custom logic if needed. +Due to the usage of **Interceptors** the generator requires .NET 10.0 and above, matching bUnit's minimum supported target framework. The generator does create a `partial` class, so it can be extended with custom logic if needed. ## Component stub generator via `ComponentStubAttribute` diff --git a/docs/site/docs/getting-started/create-test-project.md b/docs/site/docs/getting-started/create-test-project.md index a3b526ada..f1b9c558a 100644 --- a/docs/site/docs/getting-started/create-test-project.md +++ b/docs/site/docs/getting-started/create-test-project.md @@ -148,10 +148,10 @@ dotnet add package bunit --version #{NBGV_NuGetPackageVersion}# The test projects setting needs to be set to the following: - the project's SDK needs to be set to `Microsoft.NET.Sdk.Razor` (this does not work with **TUnit** - a more detailed explanation can be found below) -- set the `` to `net8.0` +- set the `` to `net10.0` > [!NOTE] -> bUnit works with `net8.0` and above as well. +> bUnit works with `net10.0` and above as well. To do so, change the first part of the test projects `.csproj` file to look like this.: @@ -159,7 +159,7 @@ To do so, change the first part of the test projects `.csproj` file to look like - net8.0 + net10.0 ... @@ -182,7 +182,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false @@ -211,7 +211,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false Exe @@ -241,7 +241,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false @@ -267,7 +267,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false @@ -293,7 +293,7 @@ The result should be a test project with a `.csproj` that looks like this (non b - net8.0 + net10.0 enable false false diff --git a/docs/site/docs/migrations/2to3.md b/docs/site/docs/migrations/2to3.md new file mode 100644 index 000000000..1422b60c0 --- /dev/null +++ b/docs/site/docs/migrations/2to3.md @@ -0,0 +1,18 @@ +--- +uid: migrating-from-2-to-3 +title: Migrating from 2.x to 3.x +--- + +# Migrating from bUnit 2.x to 3.x +This document describes the changes made in bUnit 3.x that may affect existing tests written for bUnit 2.x. + +## Dropped support for .NET 8 and .NET 9 + +bUnit 3.x drops support for `net8.0` and `net9.0`. The minimum supported target framework is now `net10.0`, and `net11.0` is also supported. + +To migrate, update your test project's `` (or ``) to `net10.0` or later: + +```diff +- net8.0 ++ net10.0 +``` \ No newline at end of file diff --git a/docs/site/docs/migrations/index.md b/docs/site/docs/migrations/index.md index 35f8abeae..4969e3e43 100644 --- a/docs/site/docs/migrations/index.md +++ b/docs/site/docs/migrations/index.md @@ -7,4 +7,5 @@ title: Migrations This section covers the migration across major versions of bUnit. The mirations themselves also list the link to the old version of the documentation (including the old API documentation). + - - \ No newline at end of file diff --git a/docs/site/docs/providing-input/seeding-assets.md b/docs/site/docs/providing-input/seeding-assets.md index af523698a..d821c04a8 100644 --- a/docs/site/docs/providing-input/seeding-assets.md +++ b/docs/site/docs/providing-input/seeding-assets.md @@ -5,7 +5,7 @@ title: Seeding static assets (Assets) # Seeding static assets (`Assets`) -This article explains how to seed the `Assets` property of components under test in bUnit. This is supported for .NET 9 and later. +This article explains how to seed the `Assets` property of components under test in bUnit. Since .NET 9, components can access static assets mapped by [`MapStaticAssets`](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/map-static-files?view=aspnetcore-9.0) through the [`ComponentBase.Assets`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.componentbase.assets?view=aspnetcore-9.0) property, e.g. to resolve fingerprinted URLs: diff --git a/docs/site/docs/toc.md b/docs/site/docs/toc.md index 53fe7e811..982f84898 100644 --- a/docs/site/docs/toc.md +++ b/docs/site/docs/toc.md @@ -37,6 +37,7 @@ ## [bunit.generators](xref:bunit-generators) # [Migrations](xref:migrations) +## [2.x to 3.x](xref:migrating-from-2-to-3) ## [1.x to 2.x](xref:migrating-from-1-to-2) # [Miscellaneous testing tips](xref:misc-test-tips) diff --git a/src/bunit.generators.internal/README.md b/src/bunit.generators.internal/README.md index 76af51e46..3031defd9 100644 --- a/src/bunit.generators.internal/README.md +++ b/src/bunit.generators.internal/README.md @@ -9,5 +9,5 @@ dotnet build-server shutdown A good way to quickly see if the generate is producing output: ``` -dotnet build-server shutdown && dotnet clean && dotnet test -p:TargetFramework=net8.0 +dotnet build-server shutdown && dotnet clean && dotnet test -p:TargetFramework=net10.0 ``` diff --git a/src/bunit.generators/README.md b/src/bunit.generators/README.md index 5211e1bfd..b852bfa0f 100644 --- a/src/bunit.generators/README.md +++ b/src/bunit.generators/README.md @@ -45,12 +45,12 @@ To use the generator, the **Interceptor** feature has to be used inside the cspr ```xml - net8.0 + net10.0 $(InterceptorsPreviewNamespaces);Bunit ``` -This limits the usage to .NET 8 and above. +This limits the usage to .NET 10 and above, matching bUnit's minimum supported target framework. ## `ComponentStubAttribute` This generator adds the ability to automatically generate stubs for a given type via an attribute. diff --git a/src/bunit.template/template/.template.config/dotnetcli.host.json b/src/bunit.template/template/.template.config/dotnetcli.host.json index ced81d900..d51839f87 100644 --- a/src/bunit.template/template/.template.config/dotnetcli.host.json +++ b/src/bunit.template/template/.template.config/dotnetcli.host.json @@ -14,9 +14,9 @@ } }, "usageExamples": [ - "--framework xunit --sdk net8.0", - "--framework xunitv3 --sdk net8.0", - "--framework nunit --sdk net8.0", - "--framework mstest --sdk net8.0" + "--framework xunit --sdk net10.0", + "--framework xunitv3 --sdk net10.0", + "--framework nunit --sdk net10.0", + "--framework mstest --sdk net10.0" ] } diff --git a/src/bunit.template/template/.template.config/template.json b/src/bunit.template/template/.template.config/template.json index 90eab74ea..27b894907 100644 --- a/src/bunit.template/template/.template.config/template.json +++ b/src/bunit.template/template/.template.config/template.json @@ -94,16 +94,6 @@ "defaultValue": "net10.0", "replaces": "targetSdk", "choices": [ - { - "choice": "net8.0", - "description": ".net 8.0", - "displayName": ".net 8.0" - }, - { - "choice": "net9.0", - "description": ".net 9.0", - "displayName": ".net 9.0" - }, { "choice": "net10.0", "description": ".net 10.0", diff --git a/src/bunit.web.query/bunit.web.query.csproj b/src/bunit.web.query/bunit.web.query.csproj index c0e9bc642..2a5d108a0 100644 --- a/src/bunit.web.query/bunit.web.query.csproj +++ b/src/bunit.web.query/bunit.web.query.csproj @@ -1,7 +1,7 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit Bunit.Web.Query diff --git a/src/bunit/BunitContext.cs b/src/bunit/BunitContext.cs index 6783f63c8..f00344e2c 100644 --- a/src/bunit/BunitContext.cs +++ b/src/bunit/BunitContext.cs @@ -1,6 +1,4 @@ -#if NET9_0_OR_GREATER using System.Runtime.CompilerServices; -#endif using Bunit.Extensions; using Bunit.Rendering; using Microsoft.Extensions.Logging; @@ -161,9 +159,7 @@ public virtual IRenderedComponent Render(ActionThe type of component to find in the render tree. /// The render fragment to render. /// The . -#if NET9_0_OR_GREATER [OverloadResolutionPriority(1)] -#endif public virtual IRenderedComponent Render(RenderFragment renderFragment) where TComponent : IComponent => RenderInsideRenderTree(renderFragment); @@ -176,7 +172,6 @@ public virtual IRenderedComponent Render(RenderFragment public virtual IRenderedComponent Render(RenderFragment renderFragment) => RenderInsideRenderTree(renderFragment); -#if NET9_0_OR_GREATER /// /// Sets the for the renderer. /// @@ -201,7 +196,6 @@ public void SetRendererInfo(RendererInfo? rendererInfo) [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Using string to align with ResourceAsset")] public void AddAsset(string url, string? label = null, params ResourceAssetProperty[] properties) => Renderer.AddAsset(url, label, properties); -#endif /// /// Dummy method required to allow Blazor's compiler to generate diff --git a/src/bunit/ComponentParameterCollection.cs b/src/bunit/ComponentParameterCollection.cs index bae0ece4e..43bb31f68 100644 --- a/src/bunit/ComponentParameterCollection.cs +++ b/src/bunit/ComponentParameterCollection.cs @@ -19,13 +19,11 @@ internal class ComponentParameterCollection : ICollection, I /// public bool IsReadOnly => false; -#if NET9_0_OR_GREATER /// /// Gets or sets the that will be specified in /// the render tree for component the parameters are being passed to. /// public IComponentRenderMode? RenderMode { get; set; } -#endif /// /// Adds a to the collection. @@ -108,9 +106,7 @@ void AddComponent(RenderTreeBuilder builder) { builder.OpenComponent(0); AddAttributes(builder); -#if NET9_0_OR_GREATER builder.AddComponentRenderMode(RenderMode); -#endif builder.CloseComponent(); } diff --git a/src/bunit/ComponentParameterCollectionBuilder.cs b/src/bunit/ComponentParameterCollectionBuilder.cs index 10ff1e4bc..e623aaa82 100644 --- a/src/bunit/ComponentParameterCollectionBuilder.cs +++ b/src/bunit/ComponentParameterCollectionBuilder.cs @@ -427,7 +427,6 @@ static string TrimEnd(string source, string value) : source; } -#if NET9_0_OR_GREATER /// /// Sets (or unsets) the for the component and child components. /// @@ -438,7 +437,6 @@ public ComponentParameterCollectionBuilder SetAssignedRenderMode(ICo parameters.RenderMode = renderMode; return this; } -#endif /// /// Try to add a for a parameter with the , if diff --git a/src/bunit/JSInterop/Implementation/BunitJSObjectReference.cs b/src/bunit/JSInterop/Implementation/BunitJSObjectReference.cs index fdaaac958..7566f57fc 100644 --- a/src/bunit/JSInterop/Implementation/BunitJSObjectReference.cs +++ b/src/bunit/JSInterop/Implementation/BunitJSObjectReference.cs @@ -4,9 +4,6 @@ namespace Bunit; [SuppressMessage("Minor Code Smell", "S1939:Inheritance list should not be redundant", Justification = "By design. To make it obvious that both is implemented.")] internal sealed class BunitJSObjectReference : IJSObjectReference, IJSInProcessObjectReference -#if !NET9_0_OR_GREATER - , IJSUnmarshalledObjectReference -#endif { private BunitJSInterop JSInterop { get; } @@ -23,7 +20,6 @@ public ValueTask InvokeAsync(string identifier, object?[]? args) public ValueTask InvokeAsync(string identifier, CancellationToken cancellationToken, object?[]? args) => JSInterop.HandleInvokeAsync(identifier, cancellationToken, args); -#if NET10_0_OR_GREATER /// public ValueTask InvokeConstructorAsync(string identifier, object?[]? args) => JSInterop.HandleInvokeConstructorAsync(identifier, args); @@ -49,7 +45,6 @@ public ValueTask InvokeConstructorAsync(string identifier, C /// public void SetValue(string identifier, TValue value) => throw new NotImplementedException(); -#endif /// public TValue Invoke(string identifier, params object?[]? args) diff --git a/src/bunit/JSInterop/Implementation/BunitJSRuntime.net10.cs b/src/bunit/JSInterop/Implementation/BunitJSRuntime.net10.cs index 5fd991935..3a3e1c3d9 100644 --- a/src/bunit/JSInterop/Implementation/BunitJSRuntime.net10.cs +++ b/src/bunit/JSInterop/Implementation/BunitJSRuntime.net10.cs @@ -1,4 +1,3 @@ -#if NET10_0_OR_GREATER using Bunit.JSInterop.Implementation; namespace Bunit.JSInterop; @@ -16,4 +15,3 @@ ValueTask IJSRuntime.InvokeConstructorAsync(string identifie ValueTask IJSRuntime.InvokeConstructorAsync(string identifier, CancellationToken cancellationToken, object?[]? args) => JSInterop.HandleInvokeConstructorAsync(identifier, cancellationToken, args); } -#endif diff --git a/src/bunit/JSInterop/Implementation/BunitJSRuntime.net8.cs b/src/bunit/JSInterop/Implementation/BunitJSRuntime.net8.cs deleted file mode 100644 index 1a3a8d649..000000000 --- a/src/bunit/JSInterop/Implementation/BunitJSRuntime.net8.cs +++ /dev/null @@ -1,27 +0,0 @@ -#if !NET9_0_OR_GREATER -using Bunit.JSInterop.Implementation; - -namespace Bunit.JSInterop; - -/// -/// bUnit's implementation of . -/// -internal sealed partial class BunitJSRuntime : IJSUnmarshalledRuntime -{ - /// - public TResult InvokeUnmarshalled(string identifier) - => JSInterop.HandleInvokeUnmarshalled(identifier); - - /// - public TResult InvokeUnmarshalled(string identifier, T0 arg0) - => JSInterop.HandleInvokeUnmarshalled(identifier, arg0); - - /// - public TResult InvokeUnmarshalled(string identifier, T0 arg0, T1 arg1) - => JSInterop.HandleInvokeUnmarshalled(identifier, arg0, arg1); - - /// - public TResult InvokeUnmarshalled(string identifier, T0 arg0, T1 arg1, T2 arg2) - => JSInterop.HandleInvokeUnmarshalled(identifier, arg0, arg1, arg2); -} -#endif diff --git a/src/bunit/JSInterop/Implementation/JSRuntimeExtensions.cs b/src/bunit/JSInterop/Implementation/JSRuntimeExtensions.cs index e5d9f5159..075043e2f 100644 --- a/src/bunit/JSInterop/Implementation/JSRuntimeExtensions.cs +++ b/src/bunit/JSInterop/Implementation/JSRuntimeExtensions.cs @@ -85,7 +85,6 @@ internal static TResult HandleInvokeUnmarshalled(this Bunit .GetResult(); } -#if NET10_0_OR_GREATER internal static ValueTask HandleInvokeConstructorAsync(this BunitJSInterop jSInterop, string identifier, object?[]? args) { var invocation = new JSRuntimeInvocation(identifier, null, args, typeof(IJSObjectReference), "InvokeConstructorAsync"); @@ -98,7 +97,6 @@ internal static ValueTask HandleInvokeConstructorAsync(this var invocation = new JSRuntimeInvocation(identifier, cancellationToken, args, typeof(IJSObjectReference), "InvokeConstructorAsync"); return jSInterop.HandleInvocation(invocation); } -#endif private static string GetInvokeAsyncMethodName() => typeof(TValue) == typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult) diff --git a/src/bunit/Rendering/BunitHtmlParser.cs b/src/bunit/Rendering/BunitHtmlParser.cs index 47fcf0095..7973adeb1 100644 --- a/src/bunit/Rendering/BunitHtmlParser.cs +++ b/src/bunit/Rendering/BunitHtmlParser.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Diagnostics; +using System.Threading; using AngleSharp; using AngleSharp.Css; using AngleSharp.Dom; @@ -23,7 +24,7 @@ internal sealed class BunitHtmlParser : IDisposable private readonly IBrowsingContext context; private readonly HtmlParser htmlParser; private readonly List documents = new(); - private readonly object parserLock = new(); + private readonly Lock parserLock = new(); private bool disposed; /// diff --git a/src/bunit/Rendering/BunitRenderer.cs b/src/bunit/Rendering/BunitRenderer.cs index 46fedfb45..bae8895b3 100644 --- a/src/bunit/Rendering/BunitRenderer.cs +++ b/src/bunit/Rendering/BunitRenderer.cs @@ -4,6 +4,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; +using System.Threading; namespace Bunit.Rendering; @@ -23,7 +24,7 @@ public sealed class BunitRenderer : Renderer [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "SetDirectParameters")] private static extern void CallSetDirectParameters(ComponentState componentState, ParameterView parameters); - private readonly object renderTreeUpdateLock = new(); + private readonly Lock renderTreeUpdateLock = new(); private readonly HashSet returnedRenderedComponentIds = new(); private readonly List rootComponents = new(); @@ -60,7 +61,6 @@ private bool IsBatchInProgress /// internal int RenderCount { get; } -#if NET9_0_OR_GREATER private RendererInfo? rendererInfo; /// @@ -125,7 +125,6 @@ public void AddAsset(string url, string? label = null, params ResourceAssetPrope resourceAssets.Add(new ResourceAsset(url, props.Count > 0 ? props : null)); resourceAssetCollection = null; } -#endif /// /// Initializes a new instance of the class. @@ -338,7 +337,6 @@ protected override IComponent ResolveComponentForRenderMode(Type componentType, return componentActivator.CreateInstance(componentType); } -#if NET9_0_OR_GREATER /// protected override IComponentRenderMode? GetComponentRenderMode(IComponent component) { @@ -411,7 +409,6 @@ childRenderMode is not null return null; } } -#endif /// protected override void AddPendingTask(ComponentState? componentState, Task task) diff --git a/src/bunit/Rendering/Internal/Htmlizer.cs b/src/bunit/Rendering/Internal/Htmlizer.cs index 32bb5768e..48715ae55 100644 --- a/src/bunit/Rendering/Internal/Htmlizer.cs +++ b/src/bunit/Rendering/Internal/Htmlizer.cs @@ -113,10 +113,8 @@ int position case RenderTreeFrameType.ElementReferenceCapture: case RenderTreeFrameType.ComponentReferenceCapture: return position + 1; -#if NET8_0_OR_GREATER case RenderTreeFrameType.NamedEvent: return position + 1; -#endif default: throw new InvalidOperationException( $"Invalid element frame type '{frame.FrameType}'." diff --git a/src/bunit/Rendering/MissingRendererInfoException.cs b/src/bunit/Rendering/MissingRendererInfoException.cs index a763a0d98..dc39749a3 100644 --- a/src/bunit/Rendering/MissingRendererInfoException.cs +++ b/src/bunit/Rendering/MissingRendererInfoException.cs @@ -1,4 +1,3 @@ -#if NET9_0_OR_GREATER namespace Bunit.Rendering; /// @@ -33,4 +32,3 @@ public void SomeTestCase() HelpLink = "https://bunit.dev/docs/interaction/render-modes"; } } -#endif diff --git a/src/bunit/Rendering/RenderModeMisMatchException.cs b/src/bunit/Rendering/RenderModeMisMatchException.cs index 8187988e3..447c4e5d7 100644 --- a/src/bunit/Rendering/RenderModeMisMatchException.cs +++ b/src/bunit/Rendering/RenderModeMisMatchException.cs @@ -1,4 +1,3 @@ -#if NET9_0_OR_GREATER namespace Bunit.Rendering; /// @@ -19,4 +18,3 @@ Ensure that the render mode of the parent component matches the render mode of t HelpLink = "https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-9.0#render-mode-propagation"; } } -#endif diff --git a/src/bunit/bunit.csproj b/src/bunit/bunit.csproj index 8712df6b9..14e3353c7 100644 --- a/src/bunit/bunit.csproj +++ b/src/bunit/bunit.csproj @@ -1,6 +1,6 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit diff --git a/tests/bunit.generators.tests/bunit.generators.tests.csproj b/tests/bunit.generators.tests/bunit.generators.tests.csproj index 96775d3d7..679f1ad07 100644 --- a/tests/bunit.generators.tests/bunit.generators.tests.csproj +++ b/tests/bunit.generators.tests/bunit.generators.tests.csproj @@ -1,7 +1,7 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 OpenSource 2027-10 Bunit diff --git a/tests/bunit.testassets/DumpCapture.cs b/tests/bunit.testassets/DumpCapture.cs index 822fddf28..ca635e590 100644 --- a/tests/bunit.testassets/DumpCapture.cs +++ b/tests/bunit.testassets/DumpCapture.cs @@ -49,11 +49,7 @@ public static async Task OnFailureAsync( private static async Task CaptureDump(string testName, string testFilePath, ITestOutputHelper outputHelper) { -#if NETSTANDARD2_1 - var processId = Process.GetCurrentProcess().Id; -#else var processId = Environment.ProcessId; -#endif var dumpFilePath = Path.Combine(Directory.GetCurrentDirectory(), $"{Path.GetFileNameWithoutExtension(testFilePath)}-{testName}-wait-failed-{Guid.NewGuid()}.dmp"); // Attempt to start the dotnet-dump process var startInfo = new ProcessStartInfo @@ -72,11 +68,7 @@ private static async Task CaptureDump(string testName, string testFilePath, ITes return; } -#if NETSTANDARD2_1 - process.WaitForExit(); -#else await process.WaitForExitAsync(); -#endif var output = await process.StandardOutput.ReadToEndAsync(); var error = await process.StandardError.ReadToEndAsync(); outputHelper.WriteLine($"Dump status: {{process.ExitCode}}. Dump file: {dumpFilePath}"); diff --git a/tests/bunit.testassets/RenderModes/RendererInfoComponent.cs b/tests/bunit.testassets/RenderModes/RendererInfoComponent.cs index 9393ab3eb..02947c591 100644 --- a/tests/bunit.testassets/RenderModes/RendererInfoComponent.cs +++ b/tests/bunit.testassets/RenderModes/RendererInfoComponent.cs @@ -1,5 +1,3 @@ -#if NET9_0_OR_GREATER - namespace Bunit.TestAssets.RenderModes; public class RendererInfoComponent : ComponentBase @@ -17,4 +15,3 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) builder.CloseElement(); } } -#endif \ No newline at end of file diff --git a/tests/bunit.testassets/RenderModes/SectionOutletComponent.cs b/tests/bunit.testassets/RenderModes/SectionOutletComponent.cs index 70dd7d9a1..cc3237ebb 100644 --- a/tests/bunit.testassets/RenderModes/SectionOutletComponent.cs +++ b/tests/bunit.testassets/RenderModes/SectionOutletComponent.cs @@ -1,22 +1,16 @@ using Microsoft.AspNetCore.Components.Web; - -#if NET8_0_OR_GREATER using Microsoft.AspNetCore.Components.Sections; -#endif namespace Bunit.TestAssets.RenderModes; public class SectionOutletComponent : ComponentBase { -#if NET8_0_OR_GREATER private static readonly Guid SectionId = Guid.NewGuid(); -#endif [Parameter] public RenderFragment ChildContent { get; set; } protected override void BuildRenderTree(RenderTreeBuilder builder) { -#if NET8_0_OR_GREATER builder.OpenComponent(0); builder.AddComponentParameter(1, nameof(SectionOutlet.SectionId), SectionId); builder.AddComponentRenderMode(RenderMode.InteractiveWebAssembly); @@ -25,6 +19,5 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) builder.AddComponentParameter(11, nameof(SectionContent.SectionId), SectionId); builder.AddAttribute(12, nameof(SectionContent.ChildContent), ChildContent); builder.CloseComponent(); -#endif } } diff --git a/tests/bunit.testassets/bunit.testassets.csproj b/tests/bunit.testassets/bunit.testassets.csproj index b8d28daec..d26f5977a 100644 --- a/tests/bunit.testassets/bunit.testassets.csproj +++ b/tests/bunit.testassets/bunit.testassets.csproj @@ -1,7 +1,7 @@  - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit.TestAssets Bunit.TestAssets Library diff --git a/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs index 64859c4eb..13738d6cd 100644 --- a/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs @@ -504,190 +504,7 @@ public void Test046() exception.Invocation.Identifier.ShouldBe(identifier); exception.Invocation.Arguments.ShouldBe(args); } - -#if !NET9_0_OR_GREATER - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with one argument")] - public void Test047() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - var args = new[] { "bar" }; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar")); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBe(args); - } - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with two arguments")] - public void Test048() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - var args = new[] { "bar", "baz" }; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz")); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBe(args); - } - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with three arguments")] - public void Test049() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - var args = new[] { "bar", "baz", "bau" }; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz", "bau")); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBe(args); - } - - [Fact(DisplayName = "Mock throws exception when in strict mode and IJSUnmarshalledRuntime invocation has not been setup with zero arguments")] - public void Test050() - { - var sut = CreateSut(JSRuntimeMode.Strict); - var identifier = "func"; - - var exception = Should.Throw(() => ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier)); - exception.Invocation.Identifier.ShouldBe(identifier); - exception.Invocation.Arguments.ShouldBeEmpty(); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed one arguments.")] - public void Test055() - { - var identifier = "fooFunc"; - var args = new[] { "bar" }; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc", args); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar"); - actual.ShouldBe(expectedResult); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed two arguments.")] - public void Test056() - { - var identifier = "fooFunc"; - var args = new[] { "bar", "baz" }; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc", args); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz"); - actual.ShouldBe(expectedResult); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed three arguments.")] - public void Test057() - { - var identifier = "fooFunc"; - var args = new[] { "bar", "baz", "bao" }; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc", args); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier, "bar", "baz", "bao"); - actual.ShouldBe(expectedResult); - } - - [Fact(DisplayName = "An IJSUnmarshalledRuntime invocation should return the correct result when passed zero arguments.")] - public void Test058() - { - var identifier = "fooFunc"; - var sut = CreateSut(JSRuntimeMode.Strict); - - var expectedResult = Guid.NewGuid(); - var planned = sut.Setup("fooFunc"); - planned.SetResult(expectedResult); - - var actual = ((IJSUnmarshalledRuntime)sut.JSRuntime).InvokeUnmarshalled(identifier); - actual.ShouldBe(expectedResult); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier), then the invocation should be visible from the Invocations list"), AutoData] - public void Test310(string identifier) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - Array.Empty(), - typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0), then the invocation should be visible from the Invocations list"), AutoData] - public void Test306(string identifier, string arg0) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1), then the invocation should be visible from the Invocations list"), AutoData] - public void Test307(string identifier, string arg0, string arg1) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0, arg1); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1, arg2), then the invocation should be visible from the Invocations list"), AutoData] - public void Test308(string identifier, string arg0, string arg1, string arg2) - { - var sut = CreateSut(JSRuntimeMode.Loose); - var jsUnmarshalledRuntime = (IJSUnmarshalledRuntime)sut.JSRuntime; - - jsUnmarshalledRuntime.InvokeUnmarshalled( - identifier, arg0, arg1, arg2); - - sut.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1, arg2 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } -#endif -#if NET10_0_OR_GREATER [Fact(DisplayName = "InvokeConstructorAsync returns IJSObjectReference in loose mode without setup")] public async Task Test400() { @@ -774,5 +591,4 @@ public async Task Test406() sut.Invocations["JsClass"].ShouldHaveSingleItem() .InvocationMethodName.ShouldBe("InvokeConstructorAsync"); } -#endif } diff --git a/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs b/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs index d99bd9dd3..6342f3569 100644 --- a/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJsObjectReferenceTest.cs @@ -246,18 +246,6 @@ public void Test070() jsRuntime.ShouldBeAssignableTo(); } -#if !NET9_0_OR_GREATER - [Fact(DisplayName = "IJSObjectReference can be cast to IJSUnmarshalledObjectReference")] - public void Test071() - { - JSInterop.Mode = JSRuntimeMode.Loose; - - var jsRuntime = GetBunitJSObjectReference(); - - jsRuntime.ShouldBeAssignableTo(); - } -#endif - [Fact(DisplayName = "IJSInProcessObjectReference-invocations is handled by handlers from BunitJSInterop")] public async Task Test080() { @@ -279,114 +267,6 @@ public async Task Test080() JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(["baz"]); } -#if !NET9_0_OR_GREATER - [Fact(DisplayName = "IJSUnmarshalledObjectReference-invocations is handled by handlers from BunitJSInterop")] - [Obsolete("Because we are calling obsolete methods in test.")] - public async Task Test081() - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalled = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - await jsUnmarshalled.InvokeAsync("bar1"); - await jsUnmarshalled.InvokeAsync("bar2", "baz"); - await jsUnmarshalled.InvokeVoidAsync("bar3"); - await jsUnmarshalled.InvokeVoidAsync("bar4", "baz"); - jsUnmarshalled.Invoke("bar5"); - jsUnmarshalled.Invoke("bar6", "baz"); - jsUnmarshalled.InvokeUnmarshalled("bar7"); - jsUnmarshalled.InvokeUnmarshalled("bar8", "baz"); - jsUnmarshalled.InvokeUnmarshalled("bar9", "baz", "boo"); - jsUnmarshalled.InvokeUnmarshalled("bar10", "baz", "boo", "bah"); - - JSInterop.VerifyInvoke("bar1"); - JSInterop.VerifyInvoke("bar2").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar3"); - JSInterop.VerifyInvoke("bar4").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar5"); - JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar7"); - JSInterop.VerifyInvoke("bar8").Arguments.ShouldBe(["baz"]); - JSInterop.VerifyInvoke("bar9").Arguments.ShouldBe(["baz", "boo"]); - JSInterop.VerifyInvoke("bar10").Arguments.ShouldBe(["baz", "boo", "bah"]); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test310(string identifier) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: Array.Empty(), - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test306(string identifier, string arg0) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test307(string identifier, string arg0, string arg1) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled(identifier, arg0, arg1); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } - - [Theory(DisplayName = "When calling InvokeUnmarshalled(identifier, arg0, arg1, arg2), then the invocation should be visible from the Invocations list"), AutoData] - [Obsolete("Because we are calling obsolete methods in test.")] - public void Test308(string identifier, string arg0, string arg1, string arg2) - { - JSInterop.Mode = JSRuntimeMode.Loose; - var jsUnmarshalledRuntime = (IJSUnmarshalledObjectReference)GetBunitJSObjectReference(); - - jsUnmarshalledRuntime.InvokeUnmarshalled( - identifier, arg0, arg1, arg2); - - JSInterop.Invocations[identifier] - .ShouldHaveSingleItem() - .ShouldBe(new JSRuntimeInvocation( - identifier, - cancellationToken: null, - args: new[] { arg0, arg1, arg2 }, - resultType: typeof(string), - invocationMethodName: "InvokeUnmarshalled")); - } -#endif [Theory(DisplayName = "When calling InvokeVoidAsync, then the invocation should be visible from the Invocations list"), AutoData] public void Test302(string identifier, string[] args, CancellationToken cancellationToken) diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs index 42a7a5607..784ba7e62 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerTest.cs @@ -15,9 +15,7 @@ public void Test001(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.Items, CreateItems(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ChildContent, item => $"

{item}

")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -29,9 +27,7 @@ public void Test002(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.Items, CreateItems(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ItemContent, item => $"

{item}

")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -43,9 +39,7 @@ public void Test010(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ChildContent, item => $"

{item}

")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -57,9 +51,7 @@ public void Test011(int itemsInDataSource) { var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.ItemContent, item => $"

{item}

")); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -119,9 +111,7 @@ public void Test030(int itemsInDataSource, float itemSize, int overscanCount) .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) .Add(p => p.ItemContent, item => $"

{item}

") .Add(p => p.ItemSize, itemSize) -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.OverscanCount, overscanCount)); cut.FindAll("p").Count.ShouldBe(itemsInDataSource); @@ -134,9 +124,7 @@ public void Test040(int itemsInDataSource) var cut = Render>(ps => ps .Add(p => p.ItemsProvider, _ => ValueTask.FromResult(new ItemsProviderResult(Array.Empty(), itemsInDataSource))) .Add(p => p.ItemContent, item => @$"

{item}

") -#if NET9_0_OR_GREATER .Add(p => p.MaxItemCount, itemsInDataSource) -#endif .Add(p => p.Placeholder, _ => @"

")); cut.FindAll(".placeholder").Count.ShouldBe(itemsInDataSource); diff --git a/tests/bunit.tests/Rendering/RenderedComponentTest.cs b/tests/bunit.tests/Rendering/RenderedComponentTest.cs index f2ab250f4..3acd3feb0 100644 --- a/tests/bunit.tests/Rendering/RenderedComponentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedComponentTest.cs @@ -304,7 +304,7 @@ public void Test030() _ = cut.Nodes; cut.Render(ps => ps.AddChildContent("

1

")); // Holding the parser's lock pauses the reader after it captured the old markup but before it caches the parsed nodes. - var parserLock = typeof(BunitHtmlParser) + var parserLock = (Lock)typeof(BunitHtmlParser) .GetField("parserLock", BindingFlags.NonPublic | BindingFlags.Instance)! .GetValue(Services.GetRequiredService())!; var reader = new Thread(() => _ = cut.Nodes); diff --git a/tests/bunit.tests/bunit.tests.csproj b/tests/bunit.tests/bunit.tests.csproj index 93b44ce54..a7c0e5ee0 100644 --- a/tests/bunit.tests/bunit.tests.csproj +++ b/tests/bunit.tests/bunit.tests.csproj @@ -1,7 +1,7 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit Bunit.Tests diff --git a/tests/bunit.web.query.tests/bunit.web.query.tests.csproj b/tests/bunit.web.query.tests/bunit.web.query.tests.csproj index dc2b89628..7ada40bcd 100644 --- a/tests/bunit.web.query.tests/bunit.web.query.tests.csproj +++ b/tests/bunit.web.query.tests/bunit.web.query.tests.csproj @@ -1,7 +1,7 @@ - net8.0;net9.0;net10.0;net11.0 + net10.0;net11.0 Bunit Bunit.Web.Query.Tests From b1fe41cbaf02008fe53d2ca99e9c8601d2344117 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 5 Sep 2026 18:54:32 +0200 Subject: [PATCH 3/7] fix: Drop obsolete/deprecated objects Fixes #1887 --- docs/site/docs/interaction/render-modes.md | 6 +-- docs/site/docs/migrations/2to3.md | 10 ++++- .../template/CounterCSharpTest.cs | 1 - .../template/CounterRazorTests.razor | 1 - src/bunit/BunitContext.Obsoletes.cs | 24 ----------- .../WaitForHelpers/WaitForFailedException.cs | 2 +- src/bunit/RemovedInFutureVersionAttribute.cs | 7 ---- .../Rendering/MissingRendererInfoException.cs | 4 +- src/bunit/TestContext.cs | 7 ---- .../BunitAuthorizationExtensions.cs | 8 ---- .../BunitSignOutSessionStateManager.cs | 42 ------------------- .../BunitSignOutSessionStateManagerTest.cs | 31 -------------- 12 files changed, 15 insertions(+), 128 deletions(-) delete mode 100644 src/bunit/BunitContext.Obsoletes.cs delete mode 100644 src/bunit/RemovedInFutureVersionAttribute.cs delete mode 100644 src/bunit/TestContext.cs delete mode 100644 src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs delete mode 100644 tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs diff --git a/docs/site/docs/interaction/render-modes.md b/docs/site/docs/interaction/render-modes.md index d019abba6..45ca1d70f 100644 --- a/docs/site/docs/interaction/render-modes.md +++ b/docs/site/docs/interaction/render-modes.md @@ -75,7 +75,7 @@ public void StaticRendering() # [Razor test code](#tab/razor) ```razor -@inherits TestContext +@inherits BunitContext @code { [Fact] public void InteractiveServer() @@ -108,7 +108,7 @@ public void StaticRendering() *** ## Setting the `RendererInfo` during testing -To control the `ComponentBase.RendererInfo` property during testing, use the method on the `TestContext` class. The `SetRendererInfo` method takes an nullable `RendererInfo` object as a parameter. Passing `null` will set the `ComponentBase.RendererInfo` to `null`. +To control the `ComponentBase.RendererInfo` property during testing, use the method on the `BunitContext` class. The `SetRendererInfo` method takes an nullable `RendererInfo` object as a parameter. Passing `null` will set the `ComponentBase.RendererInfo` to `null`. A component (`AssistentComponent.razor`) might check if interactivity is given to enable a button: @@ -154,4 +154,4 @@ public void SimulatingInteractiveServerRendering() ``` > [!NOTE] -> If a component under test uses the `ComponentBase.RendererInfo` property and the `SetRendererInfo` on `TestContext` hasn't been passed in a `RendererInfo` object, the renderer will throw an exception. \ No newline at end of file +> If a component under test uses the `ComponentBase.RendererInfo` property and the `SetRendererInfo` on `BunitContext` hasn't been passed in a `RendererInfo` object, the renderer will throw an exception. \ No newline at end of file diff --git a/docs/site/docs/migrations/2to3.md b/docs/site/docs/migrations/2to3.md index 1422b60c0..5c1e3c4d7 100644 --- a/docs/site/docs/migrations/2to3.md +++ b/docs/site/docs/migrations/2to3.md @@ -15,4 +15,12 @@ To migrate, update your test project's `` (or `net8.0 + net10.0 -``` \ No newline at end of file +``` + +## Removed obsolete and deprecated APIs + +bUnit 3.x removes APIs that were kept around for backwards compatibility with bUnit 1.x and were marked `[Obsolete]` or scheduled for removal: + +- `TestContext` class: use `BunitContext` instead. +- `RenderComponent()` and `RenderComponent(Action>?)`: use `Render()` instead. +- `BunitSignOutSessionStateManager`: this was a test double for the obsolete `SignOutSessionStateManager` from `Microsoft.AspNetCore.Components.WebAssembly.Authentication` and has been removed. `AddAuthorization()` no longer registers it in the service collection. \ No newline at end of file diff --git a/src/bunit.template/template/CounterCSharpTest.cs b/src/bunit.template/template/CounterCSharpTest.cs index fd7c78040..a9c7b4835 100644 --- a/src/bunit.template/template/CounterCSharpTest.cs +++ b/src/bunit.template/template/CounterCSharpTest.cs @@ -7,7 +7,6 @@ namespace Company.BlazorTests1; #if (testFramework_xunit) public class CounterCSharpTest : BunitContext #elif (testFramework_xunitv3) -// The full qualified namespace for bUnit TestContext is used here as xunit v3 also offers a TestContext class public class CounterCSharpTest : BunitContext #elif (testFramework_nunit) public class CounterCSharpTest : BunitContext diff --git a/src/bunit.template/template/CounterRazorTests.razor b/src/bunit.template/template/CounterRazorTests.razor index 8b02e77ce..2126a27e2 100644 --- a/src/bunit.template/template/CounterRazorTests.razor +++ b/src/bunit.template/template/CounterRazorTests.razor @@ -1,7 +1,6 @@ @*#if (testFramework_xunit) *@ @inherits BunitContext @*#elif (testFramework_xunitv3)*@ -@* The full qualified namespace for bUnit TestContext is used here as xunit v3 also offers a TestContext class *@ @inherits BunitContext @*#elif (testFramework_nunit)*@ @inherits BunitContext diff --git a/src/bunit/BunitContext.Obsoletes.cs b/src/bunit/BunitContext.Obsoletes.cs deleted file mode 100644 index 121e95636..000000000 --- a/src/bunit/BunitContext.Obsoletes.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace Bunit; - -public partial class BunitContext -{ - /// - /// Use instead. - /// - [Obsolete($"Use {nameof(Render)} instead.", true, UrlFormat = "https://bunit.dev/docs/migrations")] - public IRenderedComponent RenderComponent() - where TComponent : IComponent - { - throw new NotSupportedException($"Use {nameof(Render)}<{typeof(TComponent).Name}> instead."); - } - - /// - /// Use instead. - /// - [Obsolete($"Use {nameof(Render)} instead.", true, UrlFormat = "https://bunit.dev/docs/migrations")] - public IRenderedComponent RenderComponent(Action>? parameterBuilder) - where TComponent : IComponent - { - throw new NotSupportedException($"Use {nameof(Render)}<{typeof(TComponent).Name}> instead."); - } -} diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs b/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs index ec18da2ff..4b49c238e 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs @@ -38,7 +38,7 @@ time to complete the necessary number of renders of the component under test. and see if they match what is expected. If they do not, consider increasing the timeout, either at the individual method call level, e.g. WaitForElement("div", TimeSpan.FromSeconds(15)), - or via the static TestContext.DefaultWaitTimeout property. + or via the static BunitContext.DefaultWaitTimeout property. Check count: {checkCount}. Component render count: {componentRenderCount}. diff --git a/src/bunit/RemovedInFutureVersionAttribute.cs b/src/bunit/RemovedInFutureVersionAttribute.cs deleted file mode 100644 index 3330d9252..000000000 --- a/src/bunit/RemovedInFutureVersionAttribute.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Bunit; - -[AttributeUsage(AttributeTargets.All, Inherited = false)] -internal sealed class RemovedInFutureVersionAttribute(string todo) : Attribute -{ - public string Todo { get; } = todo; -} diff --git a/src/bunit/Rendering/MissingRendererInfoException.cs b/src/bunit/Rendering/MissingRendererInfoException.cs index dc39749a3..7eaf3c785 100644 --- a/src/bunit/Rendering/MissingRendererInfoException.cs +++ b/src/bunit/Rendering/MissingRendererInfoException.cs @@ -10,11 +10,11 @@ public sealed class MissingRendererInfoException : Exception /// public MissingRendererInfoException() : base(""" - A component under test is trying to access the 'RendererInfo' property, which has not been specified. Set it via TestContext.Renderer.SetRendererInfo. + A component under test is trying to access the 'RendererInfo' property, which has not been specified. Set it via BunitContext.Renderer.SetRendererInfo. For example: - public class SomeTestClass : TestContext + public class SomeTestClass : BunitContext { [Fact] public void SomeTestCase() diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs deleted file mode 100644 index 2f3ad5022..000000000 --- a/src/bunit/TestContext.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Bunit; - -/// -[Obsolete($"Use {nameof(BunitContext)} instead. TestContext will be removed in a future release.", false, UrlFormat = "https://bunit.dev/docs/migrations")] -public class TestContext : BunitContext -{ -} diff --git a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs index 8fad2d81d..c3dc37223 100644 --- a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs @@ -1,6 +1,5 @@ using Bunit.TestDoubles; using Microsoft.AspNetCore.Components.Authorization; -using Microsoft.AspNetCore.Components.WebAssembly.Authentication; namespace Bunit; @@ -11,16 +10,9 @@ public partial class BunitContext /// an authenticated user, as well as adding the component to the /// test contexts render tree. /// - [RemovedInFutureVersion("SignOutSessionStateManager should be removed from the container.")] public BunitAuthorizationContext AddAuthorization() { Services.AddCascadingAuthenticationState(); -#if !NET11_0_OR_GREATER - Services.AddSingleton(); -#pragma warning disable CS0618 - Services.AddSingleton(s => s.GetRequiredService()); -#pragma warning restore CS0618 -#endif var authCtx = new BunitAuthorizationContext(Services); return authCtx; } diff --git a/src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs b/src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs deleted file mode 100644 index af6d78ecf..000000000 --- a/src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs +++ /dev/null @@ -1,42 +0,0 @@ -#if !NET11_0_OR_GREATER -using Microsoft.AspNetCore.Components.WebAssembly.Authentication; - -namespace Bunit.TestDoubles; - -/// -/// Represents bUnit's own that captures calls to -/// that will help later to assert if the user was logged out -/// -#pragma warning disable CS0618 -[RemovedInFutureVersion("SignOutSessionStateManager is obsolete")] -public class BunitSignOutSessionStateManager : SignOutSessionStateManager -#pragma warning restore CS0618 -{ - /// - /// Returns true when was called, otherwise false - /// - public bool IsSignedOut { get; set; } - - /// - /// Initializes a new instance of - /// - public BunitSignOutSessionStateManager(IJSRuntime jsRuntime) : base(jsRuntime) - { - } - - /// - public override ValueTask SetSignOutState() - { - IsSignedOut = true; - return new ValueTask(); - } - - /// - public override Task ValidateSignOutState() - { - var wasSignedOut = IsSignedOut; - IsSignedOut = false; - return Task.FromResult(wasSignedOut); - } -} -#endif diff --git a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs deleted file mode 100644 index 03a40bf7a..000000000 --- a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs +++ /dev/null @@ -1,31 +0,0 @@ -#if !NET11_0_OR_GREATER -namespace Bunit.TestDoubles; - -public class BunitSignOutSessionStateManagerTest : BunitContext -{ - [Theory, AutoData] - public void ShouldSignOut(string randomUserName) - { - AddAuthorization().SetAuthorized(randomUserName); - var cut = Render(); - - cut.Find("button").Click(); - - Services.GetService()! - .IsSignedOut - .ShouldBeTrue(); - } - - [Fact] - public async Task ShouldReturnSignOutStateOnValidateSignOutState() - { - var cut = new BunitSignOutSessionStateManager(Substitute.For()); - await cut.SetSignOutState(); - - var wasValidate = await cut.ValidateSignOutState(); - - wasValidate.ShouldBeTrue(); - cut.IsSignedOut.ShouldBeFalse(); - } -} -#endif \ No newline at end of file From 871a56e619ea18dde7c5d6494274b6aa639ea81b Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 5 Sep 2026 19:16:19 +0200 Subject: [PATCH 4/7] fieat: `BunitContext.DefaultWaitTimeout` non-static Fixes #1885 --- docs/site/docs/migrations/2to3.md | 27 ++++++- src/bunit/BunitContext.cs | 8 +- .../WaitForHelpers/WaitForFailedException.cs | 2 +- .../WaitForHelpers/WaitForHelper.cs | 14 ++-- src/bunit/JSInterop/BunitJSInterop.cs | 24 ++++++ ...JSRuntimeInvocationHandlerBase{TResult}.cs | 10 ++- .../BlazorE2E/ComponentRenderingTest.cs | 2 +- .../GeneralEventDispatchExtensionsTest.cs | 2 +- ...entWaitForElementsHelperExtensions.Test.cs | 2 +- ...nentWaitForElementsHelperExtensionsTest.cs | 2 +- .../JSInterop/BunitJSInteropTimeoutTest.cs | 80 ++++++------------- .../Authorization/AuthorizationTest.cs | 2 +- 12 files changed, 101 insertions(+), 74 deletions(-) diff --git a/docs/site/docs/migrations/2to3.md b/docs/site/docs/migrations/2to3.md index 5c1e3c4d7..0ee106ebe 100644 --- a/docs/site/docs/migrations/2to3.md +++ b/docs/site/docs/migrations/2to3.md @@ -23,4 +23,29 @@ bUnit 3.x removes APIs that were kept around for backwards compatibility with bU - `TestContext` class: use `BunitContext` instead. - `RenderComponent()` and `RenderComponent(Action>?)`: use `Render()` instead. -- `BunitSignOutSessionStateManager`: this was a test double for the obsolete `SignOutSessionStateManager` from `Microsoft.AspNetCore.Components.WebAssembly.Authentication` and has been removed. `AddAuthorization()` no longer registers it in the service collection. \ No newline at end of file +- `BunitSignOutSessionStateManager`: this was a test double for the obsolete `SignOutSessionStateManager` from `Microsoft.AspNetCore.Components.WebAssembly.Authentication` and has been removed. `AddAuthorization()` no longer registers it in the service collection. + +## `BunitContext.DefaultWaitTimeout` is no longer static + +`BunitContext.DefaultWaitTimeout` used to be a `static` property, so setting it in one test affected the timeout used by every other test running in the same process, including tests running concurrently. It is now an instance property, so each `BunitContext` (and each test class deriving from it) has its own timeout, used by both `WaitForXXX` helpers and its own `JSInterop`. + +To migrate, set the timeout on the test's `BunitContext` instance instead of the static property. If every test in a class needs a longer timeout, the constructor is a good place to set it once: + +```diff + public class MyComponentTest : BunitContext + { ++ public MyComponentTest() ++ { ++ DefaultWaitTimeout = TimeSpan.FromSeconds(10); ++ } + + [Fact] + public void MyTest() + { +- BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + // ... + } + } +``` + +Setting it on a specific `BunitContext` instance (rather than a class deriving from it) works the same way: `context.DefaultWaitTimeout = TimeSpan.FromSeconds(10);`. \ No newline at end of file diff --git a/src/bunit/BunitContext.cs b/src/bunit/BunitContext.cs index f00344e2c..5671287f1 100644 --- a/src/bunit/BunitContext.cs +++ b/src/bunit/BunitContext.cs @@ -14,11 +14,10 @@ public partial class BunitContext : IDisposable, IAsyncDisposable private BunitRenderer? bunitRenderer; /// - /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. , - /// and JSInterop invocation handlers that have not been configured with results. + /// Gets or sets the default wait timeout used by "WaitFor" operations and JSInterop invocation + /// handlers that have not been configured with results. Default is 1 second. /// - /// The default is 1 second. - public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); + public TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); /// /// Gets the renderer used by the test context. @@ -63,6 +62,7 @@ public BunitContext() Services = new BunitServiceProvider(); Services.AddSingleton(_ => ComponentFactories); Services.AddDefaultBunitContextServices(this, JSInterop); + JSInterop.AttachToContext(this); } /// diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs b/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs index 4b49c238e..9099ec25c 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs @@ -38,7 +38,7 @@ time to complete the necessary number of renders of the component under test. and see if they match what is expected. If they do not, consider increasing the timeout, either at the individual method call level, e.g. WaitForElement("div", TimeSpan.FromSeconds(15)), - or via the static BunitContext.DefaultWaitTimeout property. + or via the BunitContext.DefaultWaitTimeout property. Check count: {checkCount}. Component render count: {componentRenderCount}. diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index d8e5111e1..f96d019e5 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using Bunit.Rendering; using Microsoft.Extensions.Logging; @@ -15,6 +16,9 @@ internal abstract class WaitForHelper : IDisposable private readonly Func> completeChecker; private readonly IRenderedComponent renderedComponent; private readonly ILogger> logger; + + [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by the test, not by this helper.")] + private readonly BunitContext bunitContext; private readonly BunitRenderer renderer; private readonly Timer? timer; private bool isDisposed; @@ -76,10 +80,8 @@ protected WaitForHelper( this.completeChecker = completeChecker ?? throw new ArgumentNullException(nameof(completeChecker)); logger = renderedComponent.Services.CreateLogger>(); - renderer = renderedComponent - .Services - .GetRequiredService() - .Renderer; + bunitContext = renderedComponent.Services.GetRequiredService(); + renderer = bunitContext.Renderer; checkPassedCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // Create the wait task and run the initial check @@ -280,11 +282,11 @@ private void SubscribeToOnAfterRender() renderedComponent.OnAfterRender += OnAfterRender; } - private static TimeSpan GetRuntimeTimeout(TimeSpan? timeout) + private TimeSpan GetRuntimeTimeout(TimeSpan? timeout) { return Debugger.IsAttached ? Timeout.InfiniteTimeSpan - : timeout ?? BunitContext.DefaultWaitTimeout; + : timeout ?? bunitContext.DefaultWaitTimeout; } private static Func> WrapSynchronousChecker(Func<(bool CheckPassed, T Content)> completeChecker) diff --git a/src/bunit/JSInterop/BunitJSInterop.cs b/src/bunit/JSInterop/BunitJSInterop.cs index 2dbaa9787..3f466aa1c 100644 --- a/src/bunit/JSInterop/BunitJSInterop.cs +++ b/src/bunit/JSInterop/BunitJSInterop.cs @@ -10,6 +10,8 @@ public class BunitJSInterop { private readonly Dictionary> handlers = new(); private JSRuntimeMode mode; + private BunitContext? owningContext; + private TimeSpan standaloneDefaultWaitTimeout = TimeSpan.FromSeconds(1); /// /// Gets a dictionary of all this mock has observed. @@ -27,6 +29,27 @@ public class BunitJSInterop /// public IJSRuntime JSRuntime { get; } + /// + /// Gets or sets the timeout used by unconfigured invocation handlers. Defers to the owning + /// when attached. + /// + internal TimeSpan DefaultWaitTimeout + { + get => owningContext?.DefaultWaitTimeout ?? standaloneDefaultWaitTimeout; + set + { + if (owningContext is not null) + owningContext.DefaultWaitTimeout = value; + else + standaloneDefaultWaitTimeout = value; + } + } + + /// + /// Attaches this instance to its owning . + /// + internal void AttachToContext(BunitContext context) => owningContext = context; + /// /// Initializes a new instance of the class. /// @@ -51,6 +74,7 @@ public void AddInvocationHandler(JSRuntimeInvocationHandlerBase()); handlers[resultType].Add(handler); + handler.AttachTo(this); } internal ValueTask HandleInvocation(JSRuntimeInvocation invocation) diff --git a/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs b/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs index 53026ff4d..949d4022d 100644 --- a/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs +++ b/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs @@ -16,6 +16,7 @@ public abstract class JSRuntimeInvocationHandlerBase : IDisposable private long nextInvocationId; private Task? outcome; private bool disposed; + private BunitJSInterop? owner; /// /// Gets a value indicating whether this handler is set up to handle calls to InvokeVoidAsync(string, object[]). @@ -79,7 +80,7 @@ protected internal virtual Task HandleAsync(JSRuntimeInvocation invocat if (Volatile.Read(ref outcome) is { } configured) return configured; - var timeout = BunitContext.DefaultWaitTimeout; + var timeout = DefaultWaitTimeout; if (timeout <= TimeSpan.Zero) { throw new JSRuntimeInvocationNotSetException(invocation); @@ -108,6 +109,11 @@ protected internal virtual Task HandleAsync(JSRuntimeInvocation invocat /// True if the handler can handle the invocation, false otherwise. internal bool CanHandle(JSRuntimeInvocation invocation) => invocationMatcher(invocation); + /// + /// Attaches this handler to its owning . + /// + internal void AttachTo(BunitJSInterop jsInterop) => owner = jsInterop; + /// public void Dispose() { @@ -144,6 +150,8 @@ private void CompleteAll(Task next) } } + private TimeSpan DefaultWaitTimeout => owner?.DefaultWaitTimeout ?? TimeSpan.FromSeconds(1); + private void OnTimeoutElapsed(object? state) { if (state is not PendingInvocation pending || !pendingInvocations.TryRemove(pending.Id, out _)) diff --git a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs index 9c3fb672b..132feff6a 100644 --- a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs +++ b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs @@ -20,7 +20,7 @@ public class ComponentRenderingTest : BunitContext { public ComponentRenderingTest(ITestOutputHelper outputHelper) { - BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + DefaultWaitTimeout = TimeSpan.FromSeconds(10); Services.AddXunitLogger(outputHelper); JSInterop.Mode = JSRuntimeMode.Loose; } diff --git a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs index 7bf444d62..caf4083a0 100644 --- a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs @@ -14,7 +14,7 @@ public class GeneralEventDispatchExtensionsTest : EventDispatchExtensionsTest - { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; - sut.Setup(identifier); + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = TimeSpan.FromMilliseconds(100) }; + sut.Setup(identifier); - var invocationTask = sut.JSRuntime.InvokeAsync(identifier); + var invocationTask = sut.JSRuntime.InvokeAsync(identifier); - var exception = await Should.ThrowAsync(invocationTask.AsTask()); - exception.Invocation.Identifier.ShouldBe(identifier); - }); + var exception = await Should.ThrowAsync(invocationTask.AsTask()); + exception.Invocation.Identifier.ShouldBe(identifier); } [Fact(DisplayName = "Each pending invocation times out with its own invocation")] public async Task Test310() { - await WithDefaultWaitTimeout(TimeSpan.FromMilliseconds(100), async () => - { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; - sut.Setup(_ => true); + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = TimeSpan.FromMilliseconds(100) }; + sut.Setup(_ => true); - var first = sut.JSRuntime.InvokeAsync("first").AsTask(); - var second = sut.JSRuntime.InvokeAsync("second").AsTask(); + var first = sut.JSRuntime.InvokeAsync("first").AsTask(); + var second = sut.JSRuntime.InvokeAsync("second").AsTask(); - (await Should.ThrowAsync(first)) - .Invocation.Identifier.ShouldBe("first"); - (await Should.ThrowAsync(second)) - .Invocation.Identifier.ShouldBe("second"); - }); + (await Should.ThrowAsync(first)) + .Invocation.Identifier.ShouldBe("first"); + (await Should.ThrowAsync(second)) + .Invocation.Identifier.ShouldBe("second"); } [Fact(DisplayName = "A timed out invocation does not affect later invocations")] @@ -50,18 +38,15 @@ public async Task Test311() { const string identifier = "testFunction"; - await WithDefaultWaitTimeout(TimeSpan.FromMilliseconds(100), async () => - { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; - var handler = sut.Setup(identifier); + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = TimeSpan.FromMilliseconds(100) }; + var handler = sut.Setup(identifier); - await Should.ThrowAsync( - sut.JSRuntime.InvokeAsync(identifier).AsTask()); + await Should.ThrowAsync( + sut.JSRuntime.InvokeAsync(identifier).AsTask()); - handler.SetResult(42); + handler.SetResult(42); - (await sut.JSRuntime.InvokeAsync(identifier)).ShouldBe(42); - }); + (await sut.JSRuntime.InvokeAsync(identifier)).ShouldBe(42); } [Fact(DisplayName = "Setting a result while the timeout elapses does not crash the test host")] @@ -70,21 +55,18 @@ public async Task Test312() const string identifier = "testFunction"; var timeout = TimeSpan.FromMilliseconds(2); - await WithDefaultWaitTimeout(timeout, async () => - { - var workers = Enumerable - .Range(0, Math.Max(4, Environment.ProcessorCount)) - .Select(_ => Task.Run(() => RaceResultAgainstTimeout(identifier, timeout, iterations: 250))); + var workers = Enumerable + .Range(0, Math.Max(4, Environment.ProcessorCount)) + .Select(_ => Task.Run(() => RaceResultAgainstTimeout(identifier, timeout, iterations: 250))); - await Task.WhenAll(workers); - }); + await Task.WhenAll(workers); } private static async Task RaceResultAgainstTimeout(string identifier, TimeSpan timeout, int iterations) { for (var i = 0; i < iterations; i++) { - var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict }; + var sut = new BunitJSInterop { Mode = JSRuntimeMode.Strict, DefaultWaitTimeout = timeout }; var handler = sut.Setup(identifier); var invocationTask = sut.JSRuntime.InvokeAsync(identifier).AsTask(); @@ -105,18 +87,4 @@ private static async Task RaceResultAgainstTimeout(string identifier, TimeSpan t exception.InnerException.ShouldBeOfType(); } } - - private static async Task WithDefaultWaitTimeout(TimeSpan timeout, Func test) - { - var originalTimeout = BunitContext.DefaultWaitTimeout; - BunitContext.DefaultWaitTimeout = timeout; - try - { - await test(); - } - finally - { - BunitContext.DefaultWaitTimeout = originalTimeout; - } - } } diff --git a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs index 40c2d9730..ccc00e5c1 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs @@ -6,7 +6,7 @@ public class AuthorizationTest : BunitContext { public AuthorizationTest(ITestOutputHelper outputHelper) { - BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(10); + DefaultWaitTimeout = TimeSpan.FromSeconds(10); Services.AddXunitLogger(outputHelper); } From cf74b07180147e1429dc9e3fbf556ab603e23f88 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Wed, 9 Sep 2026 11:29:36 +0200 Subject: [PATCH 5/7] docs: README update --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4208f1d12..fda024d9f 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,8 @@ To get started, head to the [getting started documentation](https://bunit.dev/do | bUnit version | .NET version | | ------------- | ------------------------------- | | 1.x | ≥ .netcore3.1 && ≤ .net 9 | -| 2.x | ≥ .net8 | +| 2.x | ≥ .net8 && ≤ .net 11 | +| 3.x | ≥ .net10 | For a migration guide, see [Upgrading bUnit](https://bunit.dev/docs/migrations/index.html). From 6c805d4017fc92e62c52153874989766d3b7c866 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 13 Sep 2026 16:31:19 +0200 Subject: [PATCH 6/7] refactor: Remove more #if older TFM --- .../bunit.testassets/Assets/AssetsIndexerComponent.razor | 6 ------ .../Assets/AssetsIterationComponent.razor | 8 -------- .../Assets/AssetsPropertiesComponent.razor | 6 ------ .../ComponentThatPrintsAssignedRenderMode.razor | 8 -------- .../RenderModes/ComponentWithServerRenderMode.razor | 8 -------- .../RenderModes/ComponentWithWebAssemblyRenderMode.razor | 8 -------- .../RenderModes/ComponentWithoutRenderMode.razor | 8 -------- tests/bunit.tests/Rendering/AssetsTest.razor | 6 ------ tests/bunit.tests/Rendering/RenderModeTest.razor | 6 ------ 9 files changed, 64 deletions(-) diff --git a/tests/bunit.testassets/Assets/AssetsIndexerComponent.razor b/tests/bunit.testassets/Assets/AssetsIndexerComponent.razor index 3b3a7cb3d..47e2c8b28 100644 --- a/tests/bunit.testassets/Assets/AssetsIndexerComponent.razor +++ b/tests/bunit.testassets/Assets/AssetsIndexerComponent.razor @@ -1,7 +1 @@ -@{ -#if NET9_0_OR_GREATER -} -@{ -#endif -} diff --git a/tests/bunit.testassets/Assets/AssetsIterationComponent.razor b/tests/bunit.testassets/Assets/AssetsIterationComponent.razor index f6dfbe340..430c4a2b7 100644 --- a/tests/bunit.testassets/Assets/AssetsIterationComponent.razor +++ b/tests/bunit.testassets/Assets/AssetsIterationComponent.razor @@ -1,15 +1,8 @@ -@{ -#if NET9_0_OR_GREATER -} @foreach (var name in SubresourceNames) { @name } -@{ -#endif -} @code { -#if NET9_0_OR_GREATER private IReadOnlyList SubresourceNames { get; set; } = Array.Empty(); protected override void OnInitialized() @@ -17,5 +10,4 @@ .Select(asset => asset.Properties?.SingleOrDefault(property => property.Name == "label")?.Value) .OfType() .ToList(); -#endif } diff --git a/tests/bunit.testassets/Assets/AssetsPropertiesComponent.razor b/tests/bunit.testassets/Assets/AssetsPropertiesComponent.razor index bb4d4ffab..453e1e472 100644 --- a/tests/bunit.testassets/Assets/AssetsPropertiesComponent.razor +++ b/tests/bunit.testassets/Assets/AssetsPropertiesComponent.razor @@ -1,6 +1,3 @@ -@{ -#if NET9_0_OR_GREATER -} @foreach (var asset in Assets) {
    @@ -10,6 +7,3 @@ }
} -@{ -#endif -} diff --git a/tests/bunit.testassets/RenderModes/ComponentThatPrintsAssignedRenderMode.razor b/tests/bunit.testassets/RenderModes/ComponentThatPrintsAssignedRenderMode.razor index effe0ff2c..98e281912 100644 --- a/tests/bunit.testassets/RenderModes/ComponentThatPrintsAssignedRenderMode.razor +++ b/tests/bunit.testassets/RenderModes/ComponentThatPrintsAssignedRenderMode.razor @@ -1,9 +1 @@ -@{ -#if NET9_0_OR_GREATER -} -

Assigned Render Mode: @AssignedRenderMode?.GetType().Name

- -@{ -#endif -} diff --git a/tests/bunit.testassets/RenderModes/ComponentWithServerRenderMode.razor b/tests/bunit.testassets/RenderModes/ComponentWithServerRenderMode.razor index dd008df6c..6e1a0fe20 100644 --- a/tests/bunit.testassets/RenderModes/ComponentWithServerRenderMode.razor +++ b/tests/bunit.testassets/RenderModes/ComponentWithServerRenderMode.razor @@ -1,7 +1,3 @@ -@{ -#if NET9_0_OR_GREATER -} - @rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveServer
@(ChildContent is not null ? "Parent assigned" : "Assigned") render mode: @AssignedRenderMode?.GetType().Name
@ChildContent @@ -9,7 +5,3 @@ @code { [Parameter] public RenderFragment? ChildContent { get; set; } } - -@{ -#endif -} diff --git a/tests/bunit.testassets/RenderModes/ComponentWithWebAssemblyRenderMode.razor b/tests/bunit.testassets/RenderModes/ComponentWithWebAssemblyRenderMode.razor index af0888317..b0acd4364 100644 --- a/tests/bunit.testassets/RenderModes/ComponentWithWebAssemblyRenderMode.razor +++ b/tests/bunit.testassets/RenderModes/ComponentWithWebAssemblyRenderMode.razor @@ -1,15 +1,7 @@ -@{ -#if NET9_0_OR_GREATER -} - @rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveWebAssembly
@(ChildContent is not null ? "Parent assigned" : "Assigned") render mode: @AssignedRenderMode?.GetType().Name
@ChildContent @code { [Parameter] public RenderFragment? ChildContent { get; set; } -} - -@{ -#endif } \ No newline at end of file diff --git a/tests/bunit.testassets/RenderModes/ComponentWithoutRenderMode.razor b/tests/bunit.testassets/RenderModes/ComponentWithoutRenderMode.razor index 6d5f7f9b7..b47217109 100644 --- a/tests/bunit.testassets/RenderModes/ComponentWithoutRenderMode.razor +++ b/tests/bunit.testassets/RenderModes/ComponentWithoutRenderMode.razor @@ -1,14 +1,6 @@ -@{ -#if NET9_0_OR_GREATER -} -
@(ChildContent is not null ? "Parent assigned" : "Assigned") render mode: @AssignedRenderMode?.GetType().Name
@ChildContent @code { [Parameter] public RenderFragment? ChildContent { get; set; } -} - -@{ -#endif } \ No newline at end of file diff --git a/tests/bunit.tests/Rendering/AssetsTest.razor b/tests/bunit.tests/Rendering/AssetsTest.razor index 3f2dd16aa..84c757c52 100644 --- a/tests/bunit.tests/Rendering/AssetsTest.razor +++ b/tests/bunit.tests/Rendering/AssetsTest.razor @@ -1,6 +1,3 @@ -@code{ - #if NET9_0_OR_GREATER -} @using Bunit.TestAssets.Assets; @inherits BunitContext @code { @@ -101,6 +98,3 @@ ex.ParamName.ShouldBe("properties"); } } -@code{ - #endif -} diff --git a/tests/bunit.tests/Rendering/RenderModeTest.razor b/tests/bunit.tests/Rendering/RenderModeTest.razor index afc865b9e..ecc32b481 100644 --- a/tests/bunit.tests/Rendering/RenderModeTest.razor +++ b/tests/bunit.tests/Rendering/RenderModeTest.razor @@ -1,6 +1,3 @@ -@code{ - #if NET9_0_OR_GREATER -} @using Bunit.TestAssets.RenderModes; @inherits BunitContext @code { @@ -171,6 +168,3 @@ act.ShouldThrow(); } } -@code{ - #endif -} From 0fd26a5c69f5a3a40f525af7d6d9203b55f76da3 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 5 Sep 2026 15:30:11 +0200 Subject: [PATCH 7/7] feat: Shared Render Tree --- CHANGELOG.md | 15 ++ .../interaction/trigger-event-handlers.md | 24 +- docs/site/docs/toc.md | 1 + .../verification/find-owning-component.md | 78 ++++++ docs/site/docs/verification/index.md | 1 + .../ElementOwningComponentExtensions.cs | 126 +++++++++ .../RenderedComponentTreeExtensions.cs | 121 +++++++++ src/bunit/Rendering/BunitRenderer.cs | 202 ++++++++++++--- src/bunit/Rendering/IRenderedComponent.cs | 29 ++- .../Internal/ComponentMarkupRange.cs | 15 ++ src/bunit/Rendering/Internal/Htmlizer.cs | 12 +- src/bunit/Rendering/Internal/NodeRangeList.cs | 35 +++ .../Rendering/Internal/RootMarkupSnapshot.cs | 240 ++++++++++++++++++ src/bunit/Rendering/RenderedComponent.cs | 160 ++++++++---- src/bunit/Rendering/RootRenderedComponent.cs | 44 ++++ .../SampleComponents/ChildOption.razor | 5 + .../SampleComponents/ChildTableRow.razor | 5 + .../SampleComponents/ChildWithButton.razor | 7 + .../SampleComponents/CounterChild.razor | 5 + .../SampleComponents/EmptyChild.razor | 1 + .../GrandParentDivWithChildButton.razor | 9 + .../SampleComponents/LeadingTextChild.razor | 1 + .../ParentDivWithChildButton.razor | 9 + .../ParentFormWithChildButton.razor | 7 + .../ParentWithEmptyChild.razor | 1 + .../ParentWithLeadingTextChild.razor | 1 + .../ParentWithTextOnlyChild.razor | 1 + .../SelectWithChildOptions.razor | 4 + .../SampleComponents/SiblingChildren.razor | 4 + .../SampleComponents/TableWithChildRows.razor | 6 + .../SampleComponents/TextOnlyChild.razor | 5 + .../ChildComponentEventBubblingTest.cs | 67 +++++ .../Extensions/ElementOwningComponentTest.cs | 116 +++++++++ .../Rendering/ComponentTreeNavigationTest.cs | 81 ++++++ .../Rendering/SharedDocumentTest.cs | 142 +++++++++++ 35 files changed, 1492 insertions(+), 88 deletions(-) create mode 100644 docs/site/docs/verification/find-owning-component.md create mode 100644 src/bunit/Extensions/ElementOwningComponentExtensions.cs create mode 100644 src/bunit/Extensions/RenderedComponentTreeExtensions.cs create mode 100644 src/bunit/Rendering/Internal/ComponentMarkupRange.cs create mode 100644 src/bunit/Rendering/Internal/NodeRangeList.cs create mode 100644 src/bunit/Rendering/Internal/RootMarkupSnapshot.cs create mode 100644 src/bunit/Rendering/RootRenderedComponent.cs create mode 100644 tests/bunit.testassets/SampleComponents/ChildOption.razor create mode 100644 tests/bunit.testassets/SampleComponents/ChildTableRow.razor create mode 100644 tests/bunit.testassets/SampleComponents/ChildWithButton.razor create mode 100644 tests/bunit.testassets/SampleComponents/CounterChild.razor create mode 100644 tests/bunit.testassets/SampleComponents/EmptyChild.razor create mode 100644 tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor create mode 100644 tests/bunit.testassets/SampleComponents/LeadingTextChild.razor create mode 100644 tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor create mode 100644 tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor create mode 100644 tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor create mode 100644 tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor create mode 100644 tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor create mode 100644 tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor create mode 100644 tests/bunit.testassets/SampleComponents/SiblingChildren.razor create mode 100644 tests/bunit.testassets/SampleComponents/TableWithChildRows.razor create mode 100644 tests/bunit.testassets/SampleComponents/TextOnlyChild.razor create mode 100644 tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs create mode 100644 tests/bunit.tests/Extensions/ElementOwningComponentTest.cs create mode 100644 tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs create mode 100644 tests/bunit.tests/Rendering/SharedDocumentTest.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index e5b9f7677..3a21227b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ All notable changes to **bUnit** will be documented in this file. The project ad ## [Unreleased] +### Added + +- `INode.GetOwningComponent()` and its generic overload, which return the rendered component that rendered a DOM node. Reported by [@egil](https://github.com/egil) in #153. +- `Parent()`, `Root()`, `GetAncestors()`, `GetChildren()` and its generic overload on `IRenderedComponent`, for navigating the component tree. Reported by [@egil](https://github.com/egil) in #1180. + +### Changed + +- **Breaking:** all rendered components in a render tree now share a single DOM. Previously each rendered component parsed its own markup into its own document, so an element found through a child component had no ancestors outside that child. Consequences: + - Events raised on an element found through a child component now bubble into the markup rendered by its ancestor components, as they do in a browser. Reported by [@JelleHissink](https://github.com/JelleHissink) in #983. + - `Find` and `FindAll` on a child component evaluate positional and combinator selectors (`:first-child`, `+`, `~`, ...) against the whole tree rather than the component's markup in isolation. + - An `option` element rendered by a child component, inside a `select` element rendered by an ancestor with a matching `value` attribute, now renders as `selected`, matching what the ancestor's markup shows. + + A component whose markup starts or ends with text, or that the HTML parser relocates, still falls back to its own document, since its nodes cannot be identified in the shared one. +- Events raised on an element obtained through `FindComponent` no longer stop at the child component's own markup, so a submit button in a child component triggers the `@onsubmit` handler on the `form` element rendered by its parent. Reported by [@JelleHissink](https://github.com/JelleHissink) in #983. + ### Fixed - `DisposeComponentsAsync()` could dispose nothing when the renderer's dispatcher was busy, e.g. with a timer calling `InvokeAsync`. Reported by [@xfunc-tim-schneider](https://github.com/xfunc-tim-schneider) in #1939. Fixed by [@linkdotnet](https://github.com/linkdotnet). diff --git a/docs/site/docs/interaction/trigger-event-handlers.md b/docs/site/docs/interaction/trigger-event-handlers.md index d8eb3ff8c..cd9497303 100644 --- a/docs/site/docs/interaction/trigger-event-handlers.md +++ b/docs/site/docs/interaction/trigger-event-handlers.md @@ -105,4 +105,26 @@ Example: ```csharp await cut.Find("button").ClickAsync(); -``` \ No newline at end of file +``` +## Events bubble across component boundaries + +Every component in a render tree shares one DOM, so an element found through a child +component still has its ancestors from the parent components around it. Events therefore +bubble the same way whether the element was found from the component under test or from +one of its children: + +```csharp +var cut = Render(); + +// Both of these trigger the @onsubmit handler on the
+// rendered by . +cut.Find("button").Click(); +cut.FindComponent().Find("button").Click(); +``` + +Use `GetOwningComponent()` on any element to get the component that rendered it, which is +covered in : + +```csharp +IRenderedComponent inner = cut.Find("button").GetOwningComponent(); +``` diff --git a/docs/site/docs/toc.md b/docs/site/docs/toc.md index 982f84898..f681edec4 100644 --- a/docs/site/docs/toc.md +++ b/docs/site/docs/toc.md @@ -20,6 +20,7 @@ # [Verifying output](xref:verification) ## [Verify markup](xref:verify-markup) ## [Verify component state](xref:verify-component-state) +## [Find the component that rendered an element](xref:find-owning-component) ## [Customizing semantic comparison](xref:semantic-html-comparison) ## [Assertion of asynchronous changes](xref:async-assertion) diff --git a/docs/site/docs/verification/find-owning-component.md b/docs/site/docs/verification/find-owning-component.md new file mode 100644 index 000000000..0e33a483d --- /dev/null +++ b/docs/site/docs/verification/find-owning-component.md @@ -0,0 +1,78 @@ +--- +uid: find-owning-component +title: Finding the component that rendered an element +--- + +# Finding the component that rendered an element + +The DOM query API is often the quickest way to reach an interesting part of the rendered +output. +takes you from a node found that way back to the component that rendered it, so you can +assert on that component's state: + +```csharp +var cut = Render(); + +IRenderedComponent owner = cut.Find("li.done").GetOwningComponent(); + +owner.Instance.ShouldBeOfType(); +``` + +Use the generic overload, +, +when you know which component type you are after. It returns a strongly typed +, so the component instance and all the usual verification +methods are available: + +```csharp +var cut = Render(); + +IRenderedComponent item = cut.Find("li.done").GetOwningComponent(); + +item.Instance.IsDone.ShouldBeTrue(); +item.MarkupMatches("
  • Buy milk
  • "); +``` + +## Which component is returned + +The **innermost** component that rendered the node. Given a `` that renders a +`
      ` and a `` per entry, `cut.Find("ul").GetOwningComponent()` returns the +`` and `cut.Find("li").GetOwningComponent()` returns the ``. + +A few details worth knowing: + +- **Nodes that are not elements resolve through their closest element.** Calling it on a text + node returns the component that rendered the element containing that text. +- **Content passed as a `RenderFragment` belongs to the receiving component.** A + `ChildContent` written in the parent is rendered into the child's render tree, so + `GetOwningComponent()` names the child. This matches what the child's + already showed. +- **bUnit's own root component is never returned.** Wrapper components with no markup of their + own, such as `CascadingValue`, lose to the component inside them. + +The generic overload widens the search outwards: if the innermost component is not a +`TComponent`, it walks up the component tree until it finds one, and throws + if there is none. That makes it a concise +way to reach a specific ancestor: + +```csharp +// The
    int ComponentId { get; } + bool IsDisposed { get; } + + /// + /// Gets the root of this component's render tree. A root returns itself. + /// + IRenderedComponentRoot Root { get; } + + /// + /// Notifies subscribers that the document behind + /// was replaced, which invalidates every element previously handed out from it. + /// + void RaiseMarkupUpdated(); + /// /// Called by the owning when it finishes a render. /// - void UpdateState(bool hasRendered, bool isMarkupGenerationRequired); + void UpdateState(bool hasRendered); +} + +/// +/// The rendered component at the root of a render tree, which owns the markup and the +/// AngleSharp document every component in that tree reads from. +/// +internal interface IRenderedComponentRoot : IRenderedComponent +{ + RootMarkupSnapshot? MarkupSnapshot { get; } + + /// + /// Regenerates the markup of the entire render tree. + /// + void RegenerateMarkup(); } diff --git a/src/bunit/Rendering/Internal/ComponentMarkupRange.cs b/src/bunit/Rendering/Internal/ComponentMarkupRange.cs new file mode 100644 index 000000000..07d61902a --- /dev/null +++ b/src/bunit/Rendering/Internal/ComponentMarkupRange.cs @@ -0,0 +1,15 @@ +namespace Bunit.Rendering; + +/// +/// The half-open range [Start, End) a component occupies in the +/// markup generated for the root component of its render tree. +/// +internal readonly record struct ComponentMarkupRange(int ComponentId, int Start, int End) +{ + public bool Contains(int index) => index >= Start && index < End; +} + +/// +/// The markup generated by the and the range of it each component rendered. +/// +internal sealed record HtmlizerResult(string Markup, IReadOnlyList Ranges); diff --git a/src/bunit/Rendering/Internal/Htmlizer.cs b/src/bunit/Rendering/Internal/Htmlizer.cs index 48715ae55..7bb54ef90 100644 --- a/src/bunit/Rendering/Internal/Htmlizer.cs +++ b/src/bunit/Rendering/Internal/Htmlizer.cs @@ -52,13 +52,17 @@ public static string ToBlazorAttribute(string attributeName) return $"{BlazorAttrPrefix}{attributeName}"; } - public static string GetHtml(int componentId, BunitRenderer renderer) + public static HtmlizerResult GetHtml(int componentId, BunitRenderer renderer) { var context = new HtmlRenderingContext(renderer); var frames = context.GetRenderTreeFrames(componentId); var newPosition = RenderFrames(context, frames, 0, frames.Count); Debug.Assert(newPosition == frames.Count); - return context.Result.ToString(); + + // Added after the child components, which keeps the list in post-order. + context.Ranges.Add(new ComponentMarkupRange(componentId, 0, context.Result.Length)); + + return new HtmlizerResult(context.Result.ToString(), context.Ranges); } private static int RenderFrames( @@ -137,8 +141,10 @@ int position return position + frame.ComponentSubtreeLength; } + var startIndex = context.Result.Length; var childFrames = context.GetRenderTreeFrames(frame.ComponentId); RenderFrames(context, childFrames, 0, childFrames.Count); + context.Ranges.Add(new ComponentMarkupRange(frame.ComponentId, startIndex, context.Result.Length)); return position + frame.ComponentSubtreeLength; } @@ -407,6 +413,8 @@ public ArrayRange GetRenderTreeFrames(int componentId) public StringBuilder Result { get; } = new(); + public List Ranges { get; } = new(); + public string? ClosestSelectValueAsString { get; set; } } } diff --git a/src/bunit/Rendering/Internal/NodeRangeList.cs b/src/bunit/Rendering/Internal/NodeRangeList.cs new file mode 100644 index 000000000..483836a28 --- /dev/null +++ b/src/bunit/Rendering/Internal/NodeRangeList.cs @@ -0,0 +1,35 @@ +using System.Collections; +using AngleSharp; +using AngleSharp.Dom; + +namespace Bunit.Rendering; + +/// +/// A read-only over a range of sibling nodes. +/// +internal sealed class NodeRangeList : INodeList, IReadOnlyList +{ + public static readonly NodeRangeList Empty = new([]); + + private readonly IReadOnlyList nodes; + + public NodeRangeList(IReadOnlyList nodes) => this.nodes = nodes; + + public INode this[int index] => nodes[index]; + + public int Length => nodes.Count; + + public int Count => nodes.Count; + + public IEnumerator GetEnumerator() => nodes.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public void ToHtml(TextWriter writer, IMarkupFormatter formatter) + { + for (var i = 0; i < nodes.Count; i++) + { + nodes[i].ToHtml(writer, formatter); + } + } +} diff --git a/src/bunit/Rendering/Internal/RootMarkupSnapshot.cs b/src/bunit/Rendering/Internal/RootMarkupSnapshot.cs new file mode 100644 index 000000000..6a2ef2759 --- /dev/null +++ b/src/bunit/Rendering/Internal/RootMarkupSnapshot.cs @@ -0,0 +1,240 @@ +using AngleSharp.Dom; + +namespace Bunit.Rendering; + +/// +/// The markup produced for one root render tree, and the range of it each component rendered. +/// +/// +/// Shared by every component under the root, so they all read from one AngleSharp document. +/// Replaced rather than mutated, which makes its reference identity the version stamp. +/// +internal sealed class RootMarkupSnapshot +{ + private readonly BunitHtmlParser htmlParser; + private readonly Dictionary rangesById; + private readonly object gate = new(); + private INodeList? nodes; + private int[]? sourceIndices; + private IElement[]? elements; + + public string Markup { get; } + + /// + /// Gets the component ranges in post-order, i.e. a component always precedes its ancestors. + /// + public IReadOnlyList Ranges { get; } + + public int RootComponentId { get; } + + public RootMarkupSnapshot(int rootComponentId, HtmlizerResult result, BunitHtmlParser htmlParser) + { + RootComponentId = rootComponentId; + Markup = result.Markup; + Ranges = result.Ranges; + this.htmlParser = htmlParser; + + rangesById = new Dictionary(result.Ranges.Count); + foreach (var range in result.Ranges) + { + rangesById[range.ComponentId] = range; + } + } + + public INodeList Nodes + { + get + { + lock (gate) + { + return nodes ??= htmlParser.Parse(Markup); + } + } + } + + public IDocument? Document => Nodes.Length > 0 ? Nodes[0].Owner : null; + + public string GetMarkup(int componentId) + => rangesById.TryGetValue(componentId, out var range) + ? Markup[range.Start..range.End] + : string.Empty; + + public bool TryGetRange(int componentId, out ComponentMarkupRange range) + => rangesById.TryGetValue(componentId, out range); + + /// + /// Gets the nodes the component rendered, as a view into . Returns + /// when they cannot be identified there and the component needs + /// a document of its own. + /// + public bool TryGetNodeView(int componentId, out INodeList view) + { + if (!rangesById.TryGetValue(componentId, out var range)) + { + view = NodeRangeList.Empty; + return false; + } + + if (componentId == RootComponentId) + { + view = Nodes; + return true; + } + + if (range.Start == range.End) + { + view = NodeRangeList.Empty; + return true; + } + + var slice = Markup.AsSpan(range.Start, range.End - range.Start); + var firstNonWhitespace = IndexOfFirstNonWhitespace(slice); + var lastNonWhitespace = IndexOfLastNonWhitespace(slice); + + // AngleSharp merges adjacent text nodes, so leading or trailing text is fused + // into the parent's text node and no range of nodes can represent this component. + if (firstNonWhitespace < 0 || slice[firstNonWhitespace] != '<' || slice[lastNonWhitespace] != '>') + { + view = NodeRangeList.Empty; + return false; + } + + if (!TryGetElementAt(range.Start + firstNonWhitespace, out var first)) + { + view = NodeRangeList.Empty; + return false; + } + + view = CollectSiblingRun(first, range); + return true; + } + + private static NodeRangeList CollectSiblingRun(IElement first, ComponentMarkupRange range) + { + var result = new List(); + var lastElementIndex = -1; + + for (INode? node = first; node is not null; node = node.NextSibling) + { + // An element without a source position - synthesized from a stray end tag, or in a + // foreign namespace such as SVG - cannot be placed, but it is inside this markup. + if (node is IElement element && GetSourceIndex(element) is var index and >= 0 && !range.Contains(index)) + { + break; + } + + if (node is IElement) + { + lastElementIndex = result.Count; + } + + result.Add(node); + } + + // The markup is known to end with a tag, so anything after the last element is the parent's. + if (lastElementIndex + 1 < result.Count) + { + result.RemoveRange(lastElementIndex + 1, result.Count - lastElementIndex - 1); + } + + return new NodeRangeList(result); + } + + private bool TryGetElementAt(int sourceIndex, [NotNullWhen(true)] out IElement? element) + { + EnsureElementIndex(); + + var position = Array.BinarySearch(sourceIndices!, sourceIndex); + if (position < 0) + { + element = null; + return false; + } + + // The parser clones formatting elements, so several can share one source index. + while (position > 0 && sourceIndices![position - 1] == sourceIndex) + { + position--; + } + + element = elements![position]; + return true; + } + + private void EnsureElementIndex() + { + lock (gate) + { + if (sourceIndices is not null) + { + return; + } + + var found = new List(); + foreach (var node in Nodes) + { + CollectElements(node, found); + } + + found.Sort(static (x, y) => GetSourceIndex(x).CompareTo(GetSourceIndex(y))); + + sourceIndices = new int[found.Count]; + for (var i = 0; i < found.Count; i++) + { + sourceIndices[i] = GetSourceIndex(found[i]); + } + + elements = found.ToArray(); + } + + static void CollectElements(INode node, List found) + { + if (node is IElement element && GetSourceIndex(element) >= 0) + { + found.Add(element); + } + + foreach (var child in node.ChildNodes) + { + CollectElements(child, found); + } + } + } + + /// + /// Gets the index in the element was parsed from, or -1 when the + /// parser synthesized it, e.g. an implicit <tbody>. + /// + internal static int GetSourceIndex(IElement element) + => element.SourceReference?.Position.Index ?? -1; + +#if !NET11_0_OR_GREATER + private static int IndexOfLastNonWhitespace(ReadOnlySpan value) + { + for (var i = value.Length - 1; i >= 0; i--) + { + if (!char.IsWhiteSpace(value[i])) + return i; + } + + return -1; + } + + private static int IndexOfFirstNonWhitespace(ReadOnlySpan value) + { + for (var i = 0; i < value.Length; i++) + { + if (!char.IsWhiteSpace(value[i])) + return i; + } + + return -1; + } +#else + private static int IndexOfFirstNonWhitespace(ReadOnlySpan value) + => value.IndexOfAnyExceptWhiteSpace(); + + private static int IndexOfLastNonWhitespace(ReadOnlySpan value) + => value.LastIndexOfAnyExceptWhiteSpace(); +#endif +} diff --git a/src/bunit/Rendering/RenderedComponent.cs b/src/bunit/Rendering/RenderedComponent.cs index 22e98e1d2..ab98ab22c 100644 --- a/src/bunit/Rendering/RenderedComponent.cs +++ b/src/bunit/Rendering/RenderedComponent.cs @@ -7,18 +7,24 @@ namespace Bunit; /// /// Represents a rendered component. /// +/// +/// The markup and the AngleSharp document belong to the root of the render tree and are +/// shared by every component in it; this type exposes the slice of both that this +/// component rendered. See . +/// [DebuggerDisplay("Component={typeof(TComponent).Name,nq},RenderCount={RenderCount}")] -internal sealed class RenderedComponent : ComponentState, IRenderedComponent, IRenderedComponent +internal class RenderedComponent : ComponentState, IRenderedComponent, IRenderedComponent where TComponent : IComponent { - private readonly BunitRenderer renderer; private readonly TComponent instance; + private readonly object sliceGate = new(); + private readonly IRenderedComponentRoot? renderTreeRoot; + private Slice? slice; - [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by BunitServiceProvider, disposed by it.")] - private readonly BunitHtmlParser htmlParser; + private protected BunitRenderer OwningRenderer { get; } - private string markup = string.Empty; - private MarkupNodes? latestRenderNodes; + [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by BunitServiceProvider, disposed by it.")] + private protected BunitHtmlParser HtmlParser { get; } /// /// Gets the component under test. @@ -37,6 +43,10 @@ public TComponent Instance /// public bool IsDisposed { get; private set; } + /// + public virtual IRenderedComponentRoot Root => renderTreeRoot + ?? throw new InvalidOperationException("A rendered component that is not a render tree root always has a parent."); + /// /// Gets the HTML markup from the rendered fragment/component. /// @@ -45,11 +55,7 @@ public string Markup get { EnsureComponentNotDisposed(); - // Volatile read is necessary to ensure the updated markup - // is available across CPU cores. Without it, the pointer to the - // markup string can be stored in a CPUs register and not - // get updated when another CPU changes the string. - return Volatile.Read(ref markup); + return GetSlice()?.Markup ?? string.Empty; } } @@ -68,17 +74,7 @@ public INodeList Nodes get { EnsureComponentNotDisposed(); - // A render can finish while Markup is parsed; keying on the markup reference stops that stale parse from being cached (#1938). - // Not needed in v3: the shared render tree (#1910) binds nodes to an immutable markup snapshot. - var currentMarkup = Markup; - var cached = latestRenderNodes; - if (cached is null || !ReferenceEquals(cached.Markup, currentMarkup)) - { - cached = new MarkupNodes(currentMarkup, htmlParser.Parse(currentMarkup)); - latestRenderNodes = cached; - } - - return cached.Nodes; + return GetSlice()?.GetNodes(HtmlParser) ?? NodeRangeList.Empty; } } @@ -96,9 +92,10 @@ public RenderedComponent( : base(renderer, componentId, instance, parentComponentState) { Services = services; - this.renderer = renderer; + OwningRenderer = renderer; + HtmlParser = services.GetRequiredService(); this.instance = (TComponent)instance; - htmlParser = Services.GetRequiredService(); + renderTreeRoot = (parentComponentState as IRenderedComponent)?.Root; } /// @@ -111,45 +108,48 @@ public RenderedComponent( /// public event EventHandler? OnMarkupUpdated; - /// - /// Called by the owning when it finishes a render. - /// - public void UpdateState(bool hasRendered, bool isMarkupGenerationRequired) + /// + public void RaiseMarkupUpdated() { if (IsDisposed) return; - if (hasRendered) - { - RenderCount++; - } + OnMarkupUpdated?.Invoke(this, EventArgs.Empty); + } - if (isMarkupGenerationRequired) - { - UpdateMarkup(); - OnMarkupUpdated?.Invoke(this, EventArgs.Empty); - } + /// + public void UpdateState(bool hasRendered) + { + if (IsDisposed) + return; - // The order here is important, since consumers of the events - // expect that markup has indeed changed when OnAfterRender is invoked - // (assuming there are markup changes) if (hasRendered) + { + RenderCount++; OnAfterRender?.Invoke(this, EventArgs.Empty); + } } /// - /// Updates the markup of the rendered fragment. + /// Gets this component's slice of the current snapshot, recomputing it when + /// the snapshot has been replaced. /// - private void UpdateMarkup() + private Slice? GetSlice() { - latestRenderNodes = null; - var newMarkup = Htmlizer.GetHtml(ComponentId, renderer); - - // Volatile write is necessary to ensure the updated markup - // is available across CPU cores. Without it, the pointer to the - // markup string can be stored in a CPUs register and not - // get updated when another CPU changes the string. - Volatile.Write(ref markup, newMarkup); + lock (sliceGate) + { + var current = Root.MarkupSnapshot; + + if (current is null) + return null; + + if (slice is null || !ReferenceEquals(slice.Snapshot, current)) + { + slice = new Slice(current, this, OwningRenderer); + } + + return slice; + } } /// @@ -165,13 +165,20 @@ private void EnsureComponentNotDisposed() /// public void Dispose() { - if (IsDisposed) + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!disposing || IsDisposed) return; IsDisposed = true; - markup = string.Empty; + slice = null; OnAfterRender = null; OnMarkupUpdated = null; + OwningRenderer.OnRenderedComponentDisposed(this); } public override ValueTask DisposeAsync() @@ -180,5 +187,52 @@ public override ValueTask DisposeAsync() return base.DisposeAsync(); } - private sealed record MarkupNodes(string Markup, INodeList Nodes); + /// + /// One component's view of a . + /// + private sealed class Slice + { + private readonly RootMarkupSnapshot snapshot; + private readonly IRenderedComponent owner; + private readonly BunitRenderer renderer; + private readonly object gate = new(); + private INodeList? nodes; + + public RootMarkupSnapshot Snapshot => snapshot; + + public string Markup { get; } + + public Slice(RootMarkupSnapshot snapshot, IRenderedComponent owner, BunitRenderer renderer) + { + this.snapshot = snapshot; + this.owner = owner; + this.renderer = renderer; + Markup = snapshot.GetMarkup(owner.ComponentId); + } + + public INodeList GetNodes(BunitHtmlParser htmlParser) + { + lock (gate) + { + if (nodes is not null) + return nodes; + + if (snapshot.TryGetNodeView(owner.ComponentId, out var view)) + { + nodes = view; + return nodes; + } + + // Registered so nodes from this private document can still be traced + // back to a component by GetOwningComponent. + nodes = htmlParser.Parse(Markup); + if (nodes.Length > 0 && nodes[0].Owner is { } document) + { + renderer.RegisterPrivateDocument(document, owner); + } + + return nodes; + } + } + } } diff --git a/src/bunit/Rendering/RootRenderedComponent.cs b/src/bunit/Rendering/RootRenderedComponent.cs new file mode 100644 index 000000000..810a77b35 --- /dev/null +++ b/src/bunit/Rendering/RootRenderedComponent.cs @@ -0,0 +1,44 @@ +using Bunit.Rendering; + +namespace Bunit; + +/// +/// The rendered component of a render tree's root. It owns the markup snapshot that +/// every in the same tree reads its slice from. +/// +internal sealed class RootRenderedComponent : RenderedComponent, IRenderedComponentRoot +{ + private RootMarkupSnapshot? snapshot; + + public RootRenderedComponent( + BunitRenderer renderer, + int componentId, + IComponent instance, + IServiceProvider services) + : base(renderer, componentId, instance, services, parentComponentState: null) + { + } + + /// + public override IRenderedComponentRoot Root => this; + + /// + public RootMarkupSnapshot? MarkupSnapshot => Volatile.Read(ref snapshot); + + /// + public void RegenerateMarkup() + { + if (IsDisposed) + return; + + var html = Htmlizer.GetHtml(ComponentId, OwningRenderer); + Volatile.Write(ref snapshot, new RootMarkupSnapshot(ComponentId, html, HtmlParser)); + } + + /// + protected override void Dispose(bool disposing) + { + snapshot = null; + base.Dispose(disposing); + } +} diff --git a/tests/bunit.testassets/SampleComponents/ChildOption.razor b/tests/bunit.testassets/SampleComponents/ChildOption.razor new file mode 100644 index 000000000..9f244b2fd --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ChildOption.razor @@ -0,0 +1,5 @@ + + +@code { + [Parameter] public string Value { get; set; } = string.Empty; +} diff --git a/tests/bunit.testassets/SampleComponents/ChildTableRow.razor b/tests/bunit.testassets/SampleComponents/ChildTableRow.razor new file mode 100644 index 000000000..e2ec30bbb --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ChildTableRow.razor @@ -0,0 +1,5 @@ +@Cell + +@code { + [Parameter] public string Cell { get; set; } = "cell"; +} diff --git a/tests/bunit.testassets/SampleComponents/ChildWithButton.razor b/tests/bunit.testassets/SampleComponents/ChildWithButton.razor new file mode 100644 index 000000000..77c9d8e09 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ChildWithButton.razor @@ -0,0 +1,7 @@ + + +@code { + [Parameter] public string ButtonType { get; set; } = "button"; + + public int ClickCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/CounterChild.razor b/tests/bunit.testassets/SampleComponents/CounterChild.razor new file mode 100644 index 000000000..9ceb74bc7 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/CounterChild.razor @@ -0,0 +1,5 @@ + + +@code { + public int Count { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/EmptyChild.razor b/tests/bunit.testassets/SampleComponents/EmptyChild.razor new file mode 100644 index 000000000..bcf78df4a --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/EmptyChild.razor @@ -0,0 +1 @@ +@code { } diff --git a/tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor b/tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor new file mode 100644 index 000000000..14ffb0b01 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/GrandParentDivWithChildButton.razor @@ -0,0 +1,9 @@ +
    + +
    + +@code { + [Parameter] public bool StopPropagation { get; set; } + + public int ClickCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/LeadingTextChild.razor b/tests/bunit.testassets/SampleComponents/LeadingTextChild.razor new file mode 100644 index 000000000..f13c43287 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/LeadingTextChild.razor @@ -0,0 +1 @@ +Hello world diff --git a/tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor b/tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor new file mode 100644 index 000000000..f825322e5 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentDivWithChildButton.razor @@ -0,0 +1,9 @@ +
    + +
    + +@code { + [Parameter] public bool StopPropagation { get; set; } + + public int ClickCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor b/tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor new file mode 100644 index 000000000..32cd65176 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentFormWithChildButton.razor @@ -0,0 +1,7 @@ + + + + +@code { + public int SubmitCount { get; set; } +} diff --git a/tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor b/tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor new file mode 100644 index 000000000..14d74d9a5 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentWithEmptyChild.razor @@ -0,0 +1 @@ +
    diff --git a/tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor b/tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor new file mode 100644 index 000000000..33630436a --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentWithLeadingTextChild.razor @@ -0,0 +1 @@ +
    diff --git a/tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor b/tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor new file mode 100644 index 000000000..a34baa18a --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/ParentWithTextOnlyChild.razor @@ -0,0 +1 @@ +

    Hello world

    diff --git a/tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor b/tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor new file mode 100644 index 000000000..ce2089b65 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/SelectWithChildOptions.razor @@ -0,0 +1,4 @@ + diff --git a/tests/bunit.testassets/SampleComponents/SiblingChildren.razor b/tests/bunit.testassets/SampleComponents/SiblingChildren.razor new file mode 100644 index 000000000..4f2cace32 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/SiblingChildren.razor @@ -0,0 +1,4 @@ +
    + + +
    diff --git a/tests/bunit.testassets/SampleComponents/TableWithChildRows.razor b/tests/bunit.testassets/SampleComponents/TableWithChildRows.razor new file mode 100644 index 000000000..78193fd34 --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/TableWithChildRows.razor @@ -0,0 +1,6 @@ + + + + + +
    diff --git a/tests/bunit.testassets/SampleComponents/TextOnlyChild.razor b/tests/bunit.testassets/SampleComponents/TextOnlyChild.razor new file mode 100644 index 000000000..c3e9594dc --- /dev/null +++ b/tests/bunit.testassets/SampleComponents/TextOnlyChild.razor @@ -0,0 +1,5 @@ +@ChildText + +@code { + [Parameter] public string ChildText { get; set; } = "child-text"; +} diff --git a/tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs b/tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs new file mode 100644 index 000000000..e81e42be7 --- /dev/null +++ b/tests/bunit.tests/EventDispatchExtensions/ChildComponentEventBubblingTest.cs @@ -0,0 +1,67 @@ +namespace Bunit; + +/// +/// Verifies that events raised on an element found through a child components +/// bubble through the DOM rendered +/// by the child's ancestor components. See issue #983. +/// +public class ChildComponentEventBubblingTest : BunitContext +{ + [Fact(DisplayName = "Clicking a child component's element bubbles to the parent component's element")] + public void Test001() + { + var cut = Render(); + + cut.FindComponent().Find("button").Click(); + + cut.Instance.ClickCount.ShouldBe(1); + } + + [Fact(DisplayName = "Clicking a child component's submit button triggers the parent component's form")] + public void Test002() + { + var cut = Render(); + + cut.FindComponent().Find("button").Click(); + + cut.Instance.SubmitCount.ShouldBe(1); + } + + [Fact(DisplayName = "Bubbling from a child component's element is identical to bubbling from the parent's view of it")] + public void Test003() + { + var cut = Render(); + var child = cut.FindComponent(); + + cut.Find("button").Click(); + var (parentAfterFirst, childAfterFirst) = (cut.Instance.ClickCount, child.Instance.ClickCount); + + child.Find("button").Click(); + + cut.Instance.ClickCount.ShouldBe(parentAfterFirst + 1); + child.Instance.ClickCount.ShouldBe(childAfterFirst + 1); + } + + [Fact(DisplayName = "stopPropagation on a parent component's element stops bubbling from a child component's element")] + public void Test004() + { + var cut = Render(ps => ps.Add(p => p.StopPropagation, true)); + + cut.FindComponent().Find("button").Click(); + + cut.FindComponent().Instance.ClickCount.ShouldBe(1); + cut.Instance.ClickCount.ShouldBe(0); + } + + [Fact(DisplayName = "Events bubble through three levels of components")] + public void Test005() + { + var cut = Render(); + + cut.FindComponent().Find("button").Click(); + + cut.FindComponent().Instance.ClickCount.ShouldBe(1); + cut.FindComponent().Instance.ClickCount.ShouldBe(1); + cut.Instance.ClickCount.ShouldBe(1); + } +} diff --git a/tests/bunit.tests/Extensions/ElementOwningComponentTest.cs b/tests/bunit.tests/Extensions/ElementOwningComponentTest.cs new file mode 100644 index 000000000..cab114097 --- /dev/null +++ b/tests/bunit.tests/Extensions/ElementOwningComponentTest.cs @@ -0,0 +1,116 @@ +using AngleSharp.Dom; +using Bunit.Rendering; + +namespace Bunit.Extensions; + +/// +/// Verifies that a DOM node can be traced back to the component that +/// rendered it. See issue #153. +/// +public class ElementOwningComponentTest : BunitContext +{ + [Fact(DisplayName = "GetOwningComponent returns the component that rendered the element")] + public void Test001() + { + var cut = Render(); + + var owner = cut.Find("button").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent returns the same rendered component as FindComponent")] + public void Test002() + { + var cut = Render(); + var child = cut.FindComponent(); + + var owner = cut.Find("button").GetOwningComponent(); + + owner.ShouldBeSameAs(child); + } + + [Fact(DisplayName = "GetOwningComponent returns the parent component for an element it rendered")] + public void Test003() + { + var cut = Render(); + + var owner = cut.Find("#parent-div").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent walks outwards to the nearest component of that type")] + public void Test004() + { + var cut = Render(); + + var owner = cut.Find("button").GetOwningComponent(); + + owner.ShouldBeSameAs(cut.FindComponent()); + } + + [Fact(DisplayName = "GetOwningComponent throws when no ancestor of that type rendered the element")] + public void Test005() + { + var cut = Render(); + + Should.Throw( + () => cut.Find("button").GetOwningComponent()); + } + + [Fact(DisplayName = "GetOwningComponent resolves a descendant node to the component that rendered its element")] + public void Test006() + { + var cut = Render(); + + var owner = cut.Find("#child-row td").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent never returns a bUnit infrastructure component")] + public void Test007() + { + var cut = Render(); + + var owner = cut.Find("h1").GetOwningComponent(); + + owner.Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetOwningComponent throws for a node that was not rendered by bUnit")] + public void Test008() + { + using var parser = new Bunit.Rendering.BunitHtmlParser(); + var nodes = parser.Parse("

    foo

    "); + + Should.Throw(() => nodes[0].GetOwningComponent()); + } + + [Fact(DisplayName = "GetOwningComponent resolves an element of a component that has its own document")] + public void Test010() + { + // Markup starting with text cannot be located in the shared document, so the + // component is parsed into one of its own - both routes must still resolve. + var cut = Render(); + var child = cut.FindComponent(); + + child.Nodes[0].Owner.ShouldNotBeSameAs(cut.Nodes[0].Owner); + + child.Find("b").GetOwningComponent().ShouldBeSameAs(child); + cut.Find("b").GetOwningComponent().ShouldBeSameAs(child); + } + + [Fact(DisplayName = "GetOwningComponent resolves elements from separate render trees to their own component")] + public void Test009() + { + var first = Render(); + var second = Render(); + + first.Find("button").GetOwningComponent() + .ShouldBeSameAs(first.FindComponent()); + second.Find("button").GetOwningComponent() + .ShouldBeSameAs(second.FindComponent()); + } +} diff --git a/tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs b/tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs new file mode 100644 index 000000000..7cc940f18 --- /dev/null +++ b/tests/bunit.tests/Rendering/ComponentTreeNavigationTest.cs @@ -0,0 +1,81 @@ +namespace Bunit.Rendering; + +/// +/// Verifies navigation of the component tree. See issue #1180. +/// +public class ComponentTreeNavigationTest : BunitContext +{ + [Fact(DisplayName = "Parent returns the component that rendered this component")] + public void Test001() + { + var cut = Render(); + + var parent = cut.FindComponent().Parent(); + + parent.ShouldNotBeNull().Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "Parent of the outermost rendered component is null")] + public void Test002() + { + var cut = Render(); + + cut.Parent().ShouldBeNull(); + } + + [Fact(DisplayName = "Root returns the outermost rendered component")] + public void Test003() + { + var cut = Render(); + + var root = cut.FindComponent().Root(); + + root.ShouldBeSameAs(cut); + } + + [Fact(DisplayName = "GetChildren returns direct child components only, in render order")] + public void Test004() + { + var cut = Render(); + + var children = cut.GetChildren(); + + children.Count.ShouldBe(2); + children[0].Instance.ShouldBeOfType(); + children[1].Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetChildren does not return grandchildren")] + public void Test005() + { + var cut = Render(); + + var children = cut.GetChildren(); + + children.Count.ShouldBe(1); + children[0].Instance.ShouldBeOfType(); + } + + [Fact(DisplayName = "GetChildren returns only direct children of that type")] + public void Test006() + { + var cut = Render(); + + var children = cut.GetChildren(); + + children.Count.ShouldBe(1); + children[0].ShouldBeSameAs(cut.FindComponent()); + } + + [Fact(DisplayName = "GetAncestors returns components from the closest parent to the root")] + public void Test007() + { + var cut = Render(); + + var ancestors = cut.FindComponent().GetAncestors().ToArray(); + + ancestors.Length.ShouldBe(2); + ancestors[0].Instance.ShouldBeOfType(); + ancestors[1].Instance.ShouldBeOfType(); + } +} diff --git a/tests/bunit.tests/Rendering/SharedDocumentTest.cs b/tests/bunit.tests/Rendering/SharedDocumentTest.cs new file mode 100644 index 000000000..8529c767c --- /dev/null +++ b/tests/bunit.tests/Rendering/SharedDocumentTest.cs @@ -0,0 +1,142 @@ +using AngleSharp.Dom; +using Bunit.Web.AngleSharp; + +namespace Bunit.Rendering; + +/// +/// Verifies that all rendered components under the same root share one +/// AngleSharp document, and that components whose markup cannot be located +/// in it fall back to their own document. +/// +public class SharedDocumentTest : BunitContext +{ + [Fact(DisplayName = "A child component's element is the same instance as the parent component's view of it")] + public void Test001() + { + var cut = Render(); + + var fromParent = cut.Find("button").Unwrap(); + var fromChild = cut.FindComponent().Find("button").Unwrap(); + + fromChild.ShouldBeSameAs(fromParent); + } + + [Fact(DisplayName = "A child component's element has the parent component's element as its parent")] + public void Test002() + { + var cut = Render(); + + var button = cut.FindComponent().Find("button"); + + button.ParentElement.ShouldNotBeNull().Id.ShouldBe("parent-form"); + } + + [Fact(DisplayName = "Nodes of parent and child components come from the same document")] + public void Test003() + { + var cut = Render(); + + var child = cut.FindComponent(); + + child.Nodes[0].Owner.ShouldBeSameAs(cut.Nodes[0].Owner); + } + + [Fact(DisplayName = "Find on a child component only matches elements rendered by that component")] + public void Test004() + { + var cut = Render(); + + var child = cut.FindComponent(); + + Should.Throw(() => child.Find("#parent-div")); + } + + [Fact(DisplayName = "Markup of a child component is unaffected by the shared document")] + public void Test005() + { + var cut = Render(); + + var child = cut.FindComponent(); + + child.Markup.ShouldStartWith("(); + var child = cut.FindComponent(); + var initialNodes = child.Nodes; + + child.Nodes.ShouldBeSameAs(initialNodes); + } + + [Fact(DisplayName = "A component whose sibling re-renders gets its element wrapper refreshed")] + public void Test007() + { + var cut = Render(); + var button = cut.FindComponent().Find("button"); + + cut.Find("#counter-button").Click(); + + // The wrapper must re-resolve into the new document instead of + // exposing a node detached from the previous parse. + button.Unwrap().Owner.ShouldBeSameAs(cut.Nodes[0].Owner); + } + + [Fact(DisplayName = "A child component rendering a inside the parent's is found")] + public void Test010() + { + var cut = Render(); + + var rows = cut.FindComponents(); + + rows.Count.ShouldBe(2); + rows[0].Find("td").TextContent.ShouldBe("one"); + rows[1].Find("td").TextContent.ShouldBe("two"); + } + + [Fact(DisplayName = "A child component rendering an