From 0390263f2d6fe1e317ff4a962f3e7c4b9105981c Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Wed, 15 Jun 2022 16:35:53 +0000 Subject: [PATCH 001/100] chore: remove support for .netstandard2.1 and net5.0 --- version.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/version.json b/version.json index d009bb001..3f126705a 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": "1.31-preview", + "$schema": "https://raw.githubusercontent.com/dotnet/Nerdbank.GitVersioning/master/src/NerdBank.GitVersioning/version.schema.json", + "version": "2.0-alpha", "assemblyVersion": { "precision": "revision" }, @@ -17,9 +17,9 @@ }, "release": { "branchName": "release/v{version}", - "firstUnstableTag": "preview" + "firstUnstableTag": "alpha" }, "pathFilters": [ "./src" ] -} \ No newline at end of file +} From 45bc3af97b72f404ce81369d8a2d522147523527 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 2 Mar 2024 21:59:05 +0100 Subject: [PATCH 002/100] refactor: Remove old frameworks --- .editorconfig | 1 + .github/workflows/ci.yml | 8 -- .github/workflows/docs-deploy.yml | 4 - .github/workflows/release.yml | 4 - Directory.Build.props | 6 +- .../bunit.benchmarks.assets.csproj | 2 +- .../bunit.benchmarks/bunit.benchmarks.csproj | 2 +- bunit.sln | 1 - docs/samples/tests/Directory.Build.props | 2 +- .../tests/razor/TemplateParams1Test.razor | 16 --- .../tests/razor/TemplateParams2Test.razor | 16 --- .../xunit/ComponentFactoryExampleTest.cs | 6 +- .../xunit/CounterWithFancyParagraphTest.cs | 2 - .../tests/xunit/DisposeComponentsTest.cs | 2 - .../tests/xunit/FooBarComponentFactory.cs | 2 - .../ConditionalComponentFactory.cs | 2 - ...actory{TComponent,TSubstituteComponent}.cs | 2 - .../InstanceComponentFactory{TComponent}.cs | 2 - .../TypeBasedComponentFactory{TComponent}.cs | 2 - src/bunit.core/ComponentFactoryCollection.cs | 2 - .../ComponentParameterCollection.cs | 3 +- .../ComponentParameterCollectionBuilder.cs | 35 +---- .../ComponentFactoryCollectionExtensions.cs | 26 ++-- .../RenderedComponentRenderExtensions.cs | 15 +- .../RenderedFragmentInvokeAsyncExtensions.cs | 12 +- .../TestContextBaseRenderExtensions.cs | 6 +- src/bunit.core/IComponentFactory.cs | 5 - .../Rendering/BunitComponentActivator.cs | 5 +- src/bunit.core/Rendering/RenderEvent.cs | 3 +- src/bunit.core/Rendering/TestRenderer.cs | 74 ++-------- src/bunit.core/StringSyntaxAttribute.cs | 26 ---- .../MemberNotNullAttribute.cs | 29 ---- src/bunit.core/TestContextBase.cs | 4 - .../FakePersistentComponentState.cs | 11 +- .../FakePersistentComponentStateStore.cs | 7 - .../TestContextBaseExtensions.cs | 8 +- src/bunit.core/TestServiceProvider.cs | 23 +-- src/bunit.core/bunit.core.csproj | 26 +--- .../ComponentStubAttribute.cs | 2 - src/bunit.web.query/bunit.web.query.csproj | 30 +--- .../Asserting/CompareToExtensions.cs | 30 ++-- .../Asserting/DiffAssertExtensions.cs | 9 +- .../FocusAsyncAssertJSInteropExtensions.cs | 4 - ...ocusOnNavigateAssertJSInteropExtensions.cs | 3 - .../JSInvokeCountExpectedException.cs | 8 +- .../Asserting/JSRuntimeAssertExtensions.cs | 6 +- .../MarkupMatchesAssertExtensions.cs | 126 ++++++----------- .../ShouldBeAdditionAssertExtensions.cs | 15 +- .../ShouldBeRemovalAssertExtensions.cs | 15 +- .../ShouldBeTextChangeAssertExtensions.cs | 24 ++-- .../StubComponentFactory.cs | 2 - src/bunit.web/Diffing/DiffMarkupFormatter.cs | 3 +- .../DetailsElementEventDispatchExtensions.cs | 4 - .../DialogEventDispatchExtensions.cs | 2 - .../MouseEventDispatchExtensions.cs | 133 ------------------ .../TriggerEventDispatchExtensions.cs | 11 +- .../Extensions/ElementNotFoundException.cs | 5 +- .../Extensions/InputFile/BUnitBrowserFile.cs | 4 +- .../Extensions/InputFile/InputFileContent.cs | 8 +- .../InputFile/InputFileExtensions.cs | 10 +- .../Extensions/NodePrintExtensions.cs | 18 +-- .../Extensions/RenderedFragmentExtensions.cs | 12 +- ...tubComponentFactoryCollectionExtensions.cs | 20 +-- .../Extensions/TestRendererExtensions.cs | 9 +- .../TestServiceProviderExtensions.cs | 13 +- .../WaitForHelpers/WaitForElementsHelper.cs | 3 +- src/bunit.web/JSInterop/BunitJSInterop.cs | 27 +--- .../BunitJSInteropSetupExtensions.cs | 20 +-- .../BunitJSInteropSetupExtensions.net5.cs | 17 +-- .../JSInterop/BunitJSModuleInterop.cs | 2 - .../Implementation/BunitJSObjectReference.cs | 7 - .../Implementation/BunitJSRuntime.net5.cs | 4 +- .../Implementation/JSRuntimeExtensions.cs | 14 -- .../FocusAsyncInvocationHandler.cs | 6 - .../Implementation/FocusOnNavigateHandler.cs | 4 - .../InputFileInvocationHandler.cs | 4 +- .../JSObjectReferenceInvocationHandler.cs | 3 - ...eModeJSObjectReferenceInvocationHandler.cs | 3 - ...isableNavigationPromptInvocationHandler.cs | 2 - ...EnableNavigationPromptInvocationHandler.cs | 2 - .../VirtualizeJSRuntimeInvocationHandler.cs | 10 -- .../JSRuntimeInvocationHandler.cs | 4 - .../JSInterop/JSRuntimeInvocation.cs | 4 - .../JSRuntimeUnhandledInvocationException.cs | 6 - src/bunit.web/Rendering/BunitHtmlParser.cs | 7 +- src/bunit.web/Rendering/Internal/Htmlizer.cs | 5 +- src/bunit.web/Rendering/WebTestRenderer.cs | 13 +- src/bunit.web/TestContext.cs | 6 +- .../FakeAuthorizationExtensions.cs | 3 +- .../Authorization/FakeAuthorizationService.cs | 3 +- .../CapturedParameterView{TComponent}.cs | 5 +- .../ComponentDoubleBase{TComponent}.cs | 2 - .../Components/ParameterNotFoundException.cs | 4 +- .../Components/Stub{TComponent}.cs | 2 - .../ErrorBoundary/BunitErrorBoundaryLogger.cs | 2 - .../MissingMockStringLocalizationException.cs | 8 +- .../FakeNavigationManager.cs | 48 ------- .../NavigationManager/NavigationHistory.cs | 65 +-------- .../NavigationManager/NavigationOptions.cs | 32 ----- .../NavigationManager/NavigationState.cs | 2 - .../BunitScrollToLocationHash.cs | 2 - src/bunit.web/bunit.web.csproj | 56 +------- src/bunit/bunit.csproj | 2 +- .../ConditionalComponentFactoryTest.cs | 3 - .../GenericComponentFactoryTest.cs | 10 -- .../InstanceComponentFactoryTest.cs | 3 - .../TypeBasedComponentFactoryTest.cs | 6 +- ...omponentParameterCollectionBuilderTests.cs | 5 - .../Rendering/BunitComponentActivatorTest.cs | 4 - .../Rendering/TestRendererTest.cs | 44 +++--- .../Rendering/TestRendererTest.net5.cs | 10 -- .../TestContextBaseTest.net5.cs | 4 - .../FakePersistentComponentStateTest.cs | 10 -- .../TestServiceProviderTest.cs | 4 - .../bunit.core.tests/bunit.core.tests.csproj | 2 +- .../TaskAssertionExtensions.cs | 9 -- .../InteractiveAutoComponent.razor | 10 +- .../InteractiveServerComponent.razor | 10 +- .../InteractiveWebAssemblyComponent.razor | 10 +- .../PersistentComponentStateSample.razor.cs | 2 - .../SampleComponents/TriggerTester.cs | 3 +- .../Serilog.Sinks.XUnit/TestOutputSink.cs | 3 +- .../XUnitLoggerConfigurationExtensions.cs | 24 ++-- .../bunit.testassets/bunit.testassets.csproj | 29 +--- .../bunit.web.query.tests.csproj | 2 +- .../MarkupMatchesAssertExtensionsTest.net5.cs | 6 - .../StubComponentFactoryTest.cs | 5 +- ...ilsElementEventDispatcherExtensionsTest.cs | 3 - .../EventDispatchExtensionsTest.cs | 12 +- .../GeneralEventDispatchExtensionsTest.cs | 7 +- .../InputEventDispatchExtensionsTest.cs | 9 -- .../TriggerEventSpy.cs | 9 +- .../Extensions/InputFile/InputFileTests.cs | 4 +- .../JSInterop/BunitJSInteropTest.net5.cs | 9 +- .../JSInterop/BunitJSObjectReferenceTest.cs | 26 ++-- .../FocusAsyncInvocationHandlerTest.cs | 8 -- .../FocusOnNavigateHandlerTest.cs | 13 -- ...irtualizeJSRuntimeInvocationHandlerTest.cs | 11 +- .../JSInterop/JSRuntimeInvocationTest.cs | 6 +- ...RuntimeUnhandledInvocationExceptionTest.cs | 4 - ...meUnhandledInvocationExceptionTest.net5.cs | 8 -- .../Rendering/Internal/HtmlizerTests.net5.cs | 5 - tests/bunit.web.tests/TestContextTest.net6.cs | 8 -- .../TestAuthorizationContextTest.cs | 4 +- .../Components/CapturedParameterViewTest.cs | 2 - .../Components/ComponentDoubleBaseTest.cs | 2 - .../TestDoubles/Components/StubTest.cs | 2 - .../FakeNavigationManagerTest.cs | 41 +----- .../TestUtilities/MockingHelpers.cs | 6 +- tests/bunit.web.tests/bunit.web.tests.csproj | 2 +- 150 files changed, 268 insertions(+), 1488 deletions(-) delete mode 100644 docs/samples/tests/razor/TemplateParams1Test.razor delete mode 100644 docs/samples/tests/razor/TemplateParams2Test.razor delete mode 100644 src/bunit.core/StringSyntaxAttribute.cs delete mode 100644 src/bunit.core/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs delete mode 100644 src/bunit.web/TestDoubles/NavigationManager/NavigationOptions.cs diff --git a/.editorconfig b/.editorconfig index 1ee6999e5..5472a756f 100644 --- a/.editorconfig +++ b/.editorconfig @@ -490,6 +490,7 @@ dotnet_diagnostic.CA1062.severity = none # CA1062: Validate arguments of public dotnet_diagnostic.CA1707.severity = none # CA1707: Identifiers should not contain underscores dotnet_diagnostic.CA1812.severity = none # CA1812: Avoid uninstantiated internal classes - components under test are never instantiated directly. dotnet_diagnostic.CA1822.severity = suggestion # CA1822: Mark members as static +dotnet_diagnostic.CA1859.severity = none # CA1859: Change return type of method dotnet_diagnostic.CA2007.severity = none # CA2007: Consider calling ConfigureAwait on the awaited task # Microsoft - FxCop diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 31b34874a..5ad62e1dc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,10 +129,6 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 3.1.x - 5.0.x - 6.0.x - 7.0.x 8.0.x 9.0.x @@ -207,10 +203,6 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 3.1.x - 5.0.x - 6.0.x - 7.0.x 8.0.x 9.0.x diff --git a/.github/workflows/docs-deploy.yml b/.github/workflows/docs-deploy.yml index e8ebf51f1..5460c6a55 100644 --- a/.github/workflows/docs-deploy.yml +++ b/.github/workflows/docs-deploy.yml @@ -72,10 +72,6 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 3.1.x - 5.0.x - 6.0.x - 7.0.x 8.0.x 9.0.x diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9172732d0..2738b7e35 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -57,10 +57,6 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 3.1.x - 5.0.x - 6.0.x - 7.0.x 8.0.x 9.0.x diff --git a/Directory.Build.props b/Directory.Build.props index d9a96bfbf..6d933a4a7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,10 +2,6 @@ - 3.1.* - 5.0.* - 6.0.* - 7.0.* 8.0.* 9.0.0-* @@ -40,7 +36,7 @@ AllEnabledByDefault true - 7 + 8 true diff --git a/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj b/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj index 2362cb400..abc5199cd 100644 --- a/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj +++ b/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj @@ -1,7 +1,7 @@ - net6.0 + net8.0 enable enable diff --git a/benchmark/bunit.benchmarks/bunit.benchmarks.csproj b/benchmark/bunit.benchmarks/bunit.benchmarks.csproj index ffeb33523..1212e538f 100644 --- a/benchmark/bunit.benchmarks/bunit.benchmarks.csproj +++ b/benchmark/bunit.benchmarks/bunit.benchmarks.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net8.0 enable false diff --git a/bunit.sln b/bunit.sln index 4ce0606e1..c39a1c1ba 100644 --- a/bunit.sln +++ b/bunit.sln @@ -52,7 +52,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".workflows", ".workflows", .github\workflows\ci.yml = .github\workflows\ci.yml .github\workflows\docs-deploy.yml = .github\workflows\docs-deploy.yml .github\workflows\prepare-release.yml = .github\workflows\prepare-release.yml - .github\workflows\release-preview.yml = .github\workflows\release-preview.yml .github\workflows\release.yml = .github\workflows\release.yml EndProjectSection EndProject diff --git a/docs/samples/tests/Directory.Build.props b/docs/samples/tests/Directory.Build.props index e5b3bbe6b..9fad1a697 100644 --- a/docs/samples/tests/Directory.Build.props +++ b/docs/samples/tests/Directory.Build.props @@ -1,6 +1,6 @@ - netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 false true false diff --git a/docs/samples/tests/razor/TemplateParams1Test.razor b/docs/samples/tests/razor/TemplateParams1Test.razor deleted file mode 100644 index 612a27abb..000000000 --- a/docs/samples/tests/razor/TemplateParams1Test.razor +++ /dev/null @@ -1,16 +0,0 @@ -@inherits TestContext - -@code -{ -#if NET6_0 - [Fact] - public void Test() - { - var cut = Render(@ - - ); - } -#endif -} \ No newline at end of file diff --git a/docs/samples/tests/razor/TemplateParams2Test.razor b/docs/samples/tests/razor/TemplateParams2Test.razor deleted file mode 100644 index 3afcffd59..000000000 --- a/docs/samples/tests/razor/TemplateParams2Test.razor +++ /dev/null @@ -1,16 +0,0 @@ -@inherits TestContext - -@code -{ -#if NET6_0 - [Fact] - public void Test() - { - var cut = Render(@ - - ); - } -#endif -} \ No newline at end of file diff --git a/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs b/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs index 580ab4096..f11a8c898 100644 --- a/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs +++ b/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - using Microsoft.AspNetCore.Components.Web; using Xunit; using Bunit; @@ -24,6 +22,4 @@ public void ReplacesFooWithBarDuringTest() Assert.Equal(1, cut.FindComponents().Count); } } -} - -#endif \ No newline at end of file +} \ No newline at end of file diff --git a/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs b/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs index 94ab7a42d..565efcbfc 100644 --- a/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs +++ b/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using Xunit; using Bunit; using Moq; @@ -38,4 +37,3 @@ public void CounterShouldIncrementWhenClicked_NSubstitute() } } } -#endif \ No newline at end of file diff --git a/docs/samples/tests/xunit/DisposeComponentsTest.cs b/docs/samples/tests/xunit/DisposeComponentsTest.cs index 5e0c403b1..5b95b0317 100644 --- a/docs/samples/tests/xunit/DisposeComponentsTest.cs +++ b/docs/samples/tests/xunit/DisposeComponentsTest.cs @@ -32,7 +32,6 @@ public void ShouldCatchExceptionInDispose() Assert.Throws(act); } -#if NET5_0_OR_GREATER [Fact] public void ShouldCatchExceptionInDisposeAsync() { @@ -42,5 +41,4 @@ public void ShouldCatchExceptionInDisposeAsync() var exception = Renderer.UnhandledException.Result; Assert.IsType(exception); } -#endif } \ No newline at end of file diff --git a/docs/samples/tests/xunit/FooBarComponentFactory.cs b/docs/samples/tests/xunit/FooBarComponentFactory.cs index da18b552c..aa5cd9ce4 100644 --- a/docs/samples/tests/xunit/FooBarComponentFactory.cs +++ b/docs/samples/tests/xunit/FooBarComponentFactory.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.Docs.Samples { using System; @@ -14,4 +13,3 @@ public IComponent Create(Type componentType) => new Bar(); } } -#endif \ No newline at end of file diff --git a/src/bunit.core/ComponentFactories/ConditionalComponentFactory.cs b/src/bunit.core/ComponentFactories/ConditionalComponentFactory.cs index d490d0258..0248ea7be 100644 --- a/src/bunit.core/ComponentFactories/ConditionalComponentFactory.cs +++ b/src/bunit.core/ComponentFactories/ConditionalComponentFactory.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.ComponentFactories; internal sealed class ConditionalComponentFactory : IComponentFactory @@ -18,4 +17,3 @@ public bool CanCreate(Type componentType) public IComponent Create(Type componentType) => factory(componentType); } -#endif diff --git a/src/bunit.core/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs b/src/bunit.core/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs index dacf64c66..17dc53538 100644 --- a/src/bunit.core/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs +++ b/src/bunit.core/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.ComponentFactories; internal sealed class GenericComponentFactory : IComponentFactory @@ -9,4 +8,3 @@ internal sealed class GenericComponentFactory public IComponent Create(Type componentType) => Activator.CreateInstance()!; } -#endif diff --git a/src/bunit.core/ComponentFactories/InstanceComponentFactory{TComponent}.cs b/src/bunit.core/ComponentFactories/InstanceComponentFactory{TComponent}.cs index e1126d435..0ce047387 100644 --- a/src/bunit.core/ComponentFactories/InstanceComponentFactory{TComponent}.cs +++ b/src/bunit.core/ComponentFactories/InstanceComponentFactory{TComponent}.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.ComponentFactories; internal sealed class InstanceComponentFactory : IComponentFactory @@ -28,4 +27,3 @@ public IComponent Create(Type componentType) return instance; } } -#endif diff --git a/src/bunit.core/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs b/src/bunit.core/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs index 1d9678e73..9beb58c07 100644 --- a/src/bunit.core/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs +++ b/src/bunit.core/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.ComponentFactories; internal sealed class TypeBasedComponentFactory : IComponentFactory @@ -15,4 +14,3 @@ public bool CanCreate(Type componentType) public IComponent Create(Type componentType) => componentFactory.Invoke(); } -#endif diff --git a/src/bunit.core/ComponentFactoryCollection.cs b/src/bunit.core/ComponentFactoryCollection.cs index 9a156fdbc..9dd788300 100644 --- a/src/bunit.core/ComponentFactoryCollection.cs +++ b/src/bunit.core/ComponentFactoryCollection.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using System.Collections; namespace Bunit; @@ -91,4 +90,3 @@ public sealed class ComponentFactoryCollection : IList /// An object that can be used to iterate through the . IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)factories).GetEnumerator(); } -#endif diff --git a/src/bunit.core/ComponentParameterCollection.cs b/src/bunit.core/ComponentParameterCollection.cs index 7b248b096..f8052c5c0 100644 --- a/src/bunit.core/ComponentParameterCollection.cs +++ b/src/bunit.core/ComponentParameterCollection.cs @@ -40,8 +40,7 @@ public void Add(ComponentParameter item) /// Parameters to add. public void Add(IEnumerable parameters) { - if (parameters is null) - throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(parameters); foreach (var cp in parameters) { diff --git a/src/bunit.core/ComponentParameterCollectionBuilder.cs b/src/bunit.core/ComponentParameterCollectionBuilder.cs index f4c1fa04e..7dbb0f690 100644 --- a/src/bunit.core/ComponentParameterCollectionBuilder.cs +++ b/src/bunit.core/ComponentParameterCollectionBuilder.cs @@ -50,11 +50,8 @@ public ComponentParameterCollectionBuilder(ActionThis . public ComponentParameterCollectionBuilder Add(Expression> parameterSelector, [AllowNull] TValue value) { -#if !NET8_0_OR_GREATER - var (name, cascadingValueName, isCascading) = GetParameterInfo(parameterSelector); -#else var (name, cascadingValueName, isCascading) = GetParameterInfo(parameterSelector, value); -#endif + return isCascading ? AddCascadingValueParameter(cascadingValueName, value) : AddParameter(name, value); @@ -91,8 +88,7 @@ public ComponentParameterCollectionBuilder Add(ExpressionThis . public ComponentParameterCollectionBuilder Add(Expression?>> parameterSelector, Func markupFactory) { - if (markupFactory is null) - throw new ArgumentNullException(nameof(markupFactory)); + ArgumentNullException.ThrowIfNull(markupFactory); return Add(parameterSelector, v => b => b.AddMarkupContent(0, markupFactory(v))); } @@ -109,8 +105,7 @@ public ComponentParameterCollectionBuilder Add(Expression Add(Expression?>> parameterSelector, Func>> templateFactory) where TChildComponent : IComponent { - if (templateFactory is null) - throw new ArgumentNullException(nameof(templateFactory)); + ArgumentNullException.ThrowIfNull(templateFactory); return Add(parameterSelector, value => GetRenderFragment(templateFactory(value))); } @@ -344,17 +339,12 @@ public ComponentParameterCollectionBuilder Bind( Action changedAction, Expression>? valueExpression = null) { - #if !NET8_0_OR_GREATER - var (parameterName, _, isCascading) = GetParameterInfo(parameterSelector); - #else var (parameterName, _, isCascading) = GetParameterInfo(parameterSelector, initialValue); - #endif if (isCascading) throw new ArgumentException("Using Bind with a cascading parameter is not allowed.", parameterName); - if (changedAction is null) - throw new ArgumentNullException(nameof(changedAction)); + ArgumentNullException.ThrowIfNull(changedAction); var changedName = $"{parameterName}Changed"; var expressionName = $"{parameterName}Expression"; @@ -437,14 +427,10 @@ public bool TryAdd(string name, [AllowNull] TValue value) public ComponentParameterCollection Build() => parameters; private static (string Name, string? CascadingValueName, bool IsCascading) GetParameterInfo( - Expression> parameterSelector -#if NET8_0_OR_GREATER - , object? value -#endif + Expression> parameterSelector, object? value ) { - if (parameterSelector is null) - throw new ArgumentNullException(nameof(parameterSelector)); + ArgumentNullException.ThrowIfNull(parameterSelector); if (parameterSelector.Body is not MemberExpression { Member: PropertyInfo propInfoCandidate }) throw new ArgumentException($"The parameter selector '{parameterSelector}' does not resolve to a public property on the component '{typeof(TComponent)}'.", nameof(parameterSelector)); @@ -454,14 +440,6 @@ Expression> parameterSelector : propInfoCandidate; var paramAttr = propertyInfo?.GetCustomAttribute(inherit: true); - #if !NET8_0_OR_GREATER - var cascadingParamAttr = propertyInfo?.GetCustomAttribute(inherit: true); - - if (propertyInfo is null || (paramAttr is null && cascadingParamAttr is null)) - throw new ArgumentException($"The parameter selector '{parameterSelector}' does not resolve to a public property on the component '{typeof(TComponent)}' with a [Parameter] or [CascadingParameter] attribute.", nameof(parameterSelector)); - - return (propertyInfo.Name, CascadingValueName: cascadingParamAttr?.Name, IsCascading: cascadingParamAttr is not null); - #else var cascadingParamAttrBase = propertyInfo?.GetCustomAttribute(inherit: true); if (propertyInfo is null || (paramAttr is null && cascadingParamAttrBase is null)) @@ -494,7 +472,6 @@ static ArgumentException CreateErrorMessageForSupplyFromQuery( NavigationManager.NavigateTo(uri); """); } - #endif } private static bool HasChildContentParameter() diff --git a/src/bunit.core/Extensions/ComponentFactoryCollectionExtensions.cs b/src/bunit.core/Extensions/ComponentFactoryCollectionExtensions.cs index ec2025e02..d17d27788 100644 --- a/src/bunit.core/Extensions/ComponentFactoryCollectionExtensions.cs +++ b/src/bunit.core/Extensions/ComponentFactoryCollectionExtensions.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using Bunit.ComponentFactories; namespace Bunit; @@ -21,8 +20,7 @@ public static ComponentFactoryCollection Add(t where TComponent : IComponent where TSubstituteComponent : IComponent { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); + ArgumentNullException.ThrowIfNull(factories); factories.Add(new GenericComponentFactory()); @@ -44,10 +42,8 @@ public static ComponentFactoryCollection Add(t public static ComponentFactoryCollection Add(this ComponentFactoryCollection factories, TComponent instance) where TComponent : IComponent { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); - if (instance is null) - throw new ArgumentNullException(nameof(instance)); + ArgumentNullException.ThrowIfNull(factories); + ArgumentNullException.ThrowIfNull(instance); factories.Add(new InstanceComponentFactory(instance)); @@ -70,10 +66,8 @@ public static ComponentFactoryCollection Add(this ComponentFactoryCo public static ComponentFactoryCollection Add(this ComponentFactoryCollection factories, Func factory) where TComponent : IComponent { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); - if (factory is null) - throw new ArgumentNullException(nameof(factory)); + ArgumentNullException.ThrowIfNull(factories); + ArgumentNullException.ThrowIfNull(factory); factories.Add(new TypeBasedComponentFactory(factory)); @@ -95,16 +89,12 @@ public static ComponentFactoryCollection Add(this ComponentFactoryCo /// Thrown when , , and/or is null. public static ComponentFactoryCollection Add(this ComponentFactoryCollection factories, Predicate condition, Func factory) { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); - if (condition is null) - throw new ArgumentNullException(nameof(condition)); - if (factory is null) - throw new ArgumentNullException(nameof(factory)); + ArgumentNullException.ThrowIfNull(factories); + ArgumentNullException.ThrowIfNull(condition); + ArgumentNullException.ThrowIfNull(factory); factories.Add(new ConditionalComponentFactory(condition, factory)); return factories; } } -#endif diff --git a/src/bunit.core/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit.core/Extensions/RenderedComponentRenderExtensions.cs index 5e01c233b..a6de0a34b 100644 --- a/src/bunit.core/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit.core/Extensions/RenderedComponentRenderExtensions.cs @@ -26,8 +26,7 @@ public static void Render(this IRenderedComponentBase re public static void SetParametersAndRender(this IRenderedComponentBase renderedComponent, ParameterView parameters) where TComponent : IComponent { - if (renderedComponent is null) - throw new ArgumentNullException(nameof(renderedComponent)); + ArgumentNullException.ThrowIfNull(renderedComponent); var renderer = (TestRenderer)renderedComponent.Services.GetRequiredService().Renderer; @@ -50,10 +49,8 @@ public static void SetParametersAndRender(this IRenderedComponentBas public static void SetParametersAndRender(this IRenderedComponentBase renderedComponent, params ComponentParameter[] parameters) where TComponent : IComponent { - if (renderedComponent is null) - throw new ArgumentNullException(nameof(renderedComponent)); - if (parameters is null) - throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(renderedComponent); + ArgumentNullException.ThrowIfNull(parameters); SetParametersAndRender(renderedComponent, ToParameterView(parameters)); } @@ -67,10 +64,8 @@ public static void SetParametersAndRender(this IRenderedComponentBas public static void SetParametersAndRender(this IRenderedComponentBase renderedComponent, Action> parameterBuilder) where TComponent : IComponent { - if (renderedComponent is null) - throw new ArgumentNullException(nameof(renderedComponent)); - if (parameterBuilder is null) - throw new ArgumentNullException(nameof(parameterBuilder)); + ArgumentNullException.ThrowIfNull(renderedComponent); + ArgumentNullException.ThrowIfNull(parameterBuilder); var builder = new ComponentParameterCollectionBuilder(parameterBuilder); SetParametersAndRender(renderedComponent, ToParameterView(builder.Build())); diff --git a/src/bunit.core/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit.core/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index d9078b673..6f0b6e04c 100644 --- a/src/bunit.core/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit.core/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -15,8 +15,7 @@ public static class RenderedFragmentInvokeAsyncExtensions /// A that will be completed when the action has finished executing or is suspended by an asynchronous operation. public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Action workItem) { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); return renderedFragment .Services @@ -34,8 +33,7 @@ public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Acti /// A that will be completed when the action has finished executing. public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func workItem) { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); return renderedFragment .Services @@ -53,8 +51,7 @@ public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func /// A that will be completed when the action has finished executing, with the return value from . public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func workItem) { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); return renderedFragment .Services @@ -72,8 +69,7 @@ public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment /// A that will be completed when the action has finished executing, with the return value from . public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func> workItem) { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); return renderedFragment .Services diff --git a/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs b/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs index be5f03782..53c6abd49 100644 --- a/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs +++ b/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs @@ -17,8 +17,7 @@ public static class TestContextBaseRenderExtensions public static IRenderedComponentBase RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) where TComponent : IComponent { - if (testContext is null) - throw new ArgumentNullException(nameof(testContext)); + ArgumentNullException.ThrowIfNull(testContext); var baseResult = RenderInsideRenderTree(testContext, renderFragment); return testContext.Renderer.FindComponent(baseResult); @@ -32,8 +31,7 @@ public static IRenderedComponentBase RenderInsideRenderTreeA . public static IRenderedFragmentBase RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) { - if (testContext is null) - throw new ArgumentNullException(nameof(testContext)); + ArgumentNullException.ThrowIfNull(testContext); // Wrap fragment in a FragmentContainer so the start of the test supplied // razor fragment can be found after, and then wrap in any layout components diff --git a/src/bunit.core/IComponentFactory.cs b/src/bunit.core/IComponentFactory.cs index 50e18fee5..2cb139b87 100644 --- a/src/bunit.core/IComponentFactory.cs +++ b/src/bunit.core/IComponentFactory.cs @@ -1,7 +1,3 @@ -#if NET5_0_OR_GREATER -using System; -using Microsoft.AspNetCore.Components; - namespace Bunit; /// @@ -22,4 +18,3 @@ public interface IComponentFactory /// The type of component to create. IComponent Create(Type componentType); } -#endif diff --git a/src/bunit.core/Rendering/BunitComponentActivator.cs b/src/bunit.core/Rendering/BunitComponentActivator.cs index e7afdd5c8..400d94877 100644 --- a/src/bunit.core/Rendering/BunitComponentActivator.cs +++ b/src/bunit.core/Rendering/BunitComponentActivator.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - namespace Bunit.Rendering; internal class BunitComponentActivator : IComponentActivator @@ -47,9 +45,8 @@ private sealed class DefaultComponentActivator : IComponentActivator /// public IComponent CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type componentType) - { + { return (IComponent)Activator.CreateInstance(componentType)!; } } } -#endif diff --git a/src/bunit.core/Rendering/RenderEvent.cs b/src/bunit.core/Rendering/RenderEvent.cs index 77a823ee0..bbb410653 100644 --- a/src/bunit.core/Rendering/RenderEvent.cs +++ b/src/bunit.core/Rendering/RenderEvent.cs @@ -22,8 +22,7 @@ public sealed class RenderEvent /// A tuple of statuses indicating whether the rendered component rendered during the render cycle, if it changed or if it was disposed. public (bool Rendered, bool Changed, bool Disposed) GetRenderStatus(IRenderedFragmentBase renderedComponent) { - if (renderedComponent is null) - throw new ArgumentNullException(nameof(renderedComponent)); + ArgumentNullException.ThrowIfNull(renderedComponent); return statuses.TryGetValue(renderedComponent.ComponentId, out var status) ? (status.Rendered, status.Changed, status.Disposed) diff --git a/src/bunit.core/Rendering/TestRenderer.cs b/src/bunit.core/Rendering/TestRenderer.cs index bf7449b4e..f78298ffc 100644 --- a/src/bunit.core/Rendering/TestRenderer.cs +++ b/src/bunit.core/Rendering/TestRenderer.cs @@ -10,17 +10,11 @@ namespace Bunit.Rendering; /// public class TestRenderer : Renderer, ITestRenderer { -#if NET8_0_OR_GREATER [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")] extern static ref bool GetIsBatchInProgressField(Renderer renderer); [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "SetDirectParameters")] extern static void CallSetDirectParameters(ComponentState componentState, ParameterView parameters); -#else - private static readonly Type RendererType = typeof(Renderer); - private static readonly MethodInfo GetRequiredComponentStateMethod = RendererType.GetMethod("GetRequiredComponentState", BindingFlags.Instance | BindingFlags.NonPublic)!; - private static readonly FieldInfo IsBatchInProgressField = RendererType.GetField("_isBatchInProgress", BindingFlags.Instance | BindingFlags.NonPublic)!; -#endif private readonly object renderTreeUpdateLock = new(); private readonly Dictionary renderedComponents = new(); @@ -36,20 +30,12 @@ private bool IsBatchInProgress #pragma warning disable S1144 // Unused private types or members should be removed get { -#if NET8_0_OR_GREATER return GetIsBatchInProgressField(this); -#else - return (bool)(IsBatchInProgressField.GetValue(this) ?? false); -#endif } #pragma warning restore S1144 // Unused private types or members should be removed set { -#if NET8_0_OR_GREATER GetIsBatchInProgressField(this) = value; -#else - IsBatchInProgressField.SetValue(this, value); -#endif } } @@ -64,17 +50,6 @@ private bool IsBatchInProgress /// internal int RenderCount { get; private set; } -#if NETSTANDARD - /// - /// Initializes a new instance of the class. - /// - public TestRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory) - : base(services, loggerFactory) - { - logger = loggerFactory.CreateLogger(); - this.activator = renderedComponentActivator; - } -#elif NET5_0_OR_GREATER /// /// Initializes a new instance of the class. /// @@ -94,7 +69,6 @@ public TestRenderer(IRenderedComponentActivator renderedComponentActivator, Test logger = loggerFactory.CreateLogger(); this.activator = renderedComponentActivator; } -#endif /// public IRenderedFragmentBase RenderFragment(RenderFragment renderFragment) @@ -104,8 +78,7 @@ public IRenderedFragmentBase RenderFragment(RenderFragment renderFragment) public IRenderedComponentBase RenderComponent(ComponentParameterCollection parameters) where TComponent : IComponent { - if (parameters is null) - throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(parameters); var renderFragment = parameters.ToRenderFragment(); return Render(renderFragment, id => activator.CreateRenderedComponent(id)); @@ -117,29 +90,23 @@ public IRenderedComponentBase RenderComponent(ComponentP EventFieldInfo fieldInfo, EventArgs eventArgs) => DispatchEventAsync(eventHandlerId, fieldInfo, eventArgs, ignoreUnknownEventHandlers: false); + /// /// -#if !NET8_0_OR_GREATER - public Task DispatchEventAsync( -#else public new Task DispatchEventAsync( -#endif ulong eventHandlerId, EventFieldInfo fieldInfo, EventArgs eventArgs, bool ignoreUnknownEventHandlers) { - if (fieldInfo is null) - throw new ArgumentNullException(nameof(fieldInfo)); + ArgumentNullException.ThrowIfNull(fieldInfo); - if (disposed) - throw new ObjectDisposedException(nameof(TestRenderer)); + ObjectDisposedException.ThrowIf(disposed, this); // Calling base.DispatchEventAsync updates the render tree // if the event contains associated data. lock (renderTreeUpdateLock) { - if (disposed) - throw new ObjectDisposedException(nameof(TestRenderer)); + ObjectDisposedException.ThrowIf(disposed, this); var result = Dispatcher.InvokeAsync(() => { @@ -191,8 +158,7 @@ public IReadOnlyList> FindComponents public void DisposeComponents() { - if (disposed) - throw new ObjectDisposedException(nameof(TestRenderer)); + ObjectDisposedException.ThrowIf(disposed, this); lock (renderTreeUpdateLock) { @@ -215,7 +181,6 @@ public void DisposeComponents() } } -#if NET8_0_OR_GREATER /// protected override IComponent ResolveComponentForRenderMode(Type componentType, int? parentComponentId, IComponentActivator componentActivator, IComponentRenderMode renderMode) @@ -224,13 +189,11 @@ protected override IComponent ResolveComponentForRenderMode(Type componentType, ArgumentNullException.ThrowIfNull(componentActivator); return componentActivator.CreateInstance(componentType); } -#endif /// internal Task SetDirectParametersAsync(IRenderedFragmentBase renderedComponent, ParameterView parameters) { - if (disposed) - throw new ObjectDisposedException(nameof(TestRenderer)); + ObjectDisposedException.ThrowIf(disposed, this); var result = Dispatcher.InvokeAsync(() => { @@ -260,20 +223,11 @@ internal Task SetDirectParametersAsync(IRenderedFragmentBase renderedComponent, return result; -#if NET8_0_OR_GREATER static void SetDirectParametersViaComponentState(TestRenderer renderer, int componentId, in ParameterView parameters) { var componentState = renderer.GetComponentState(componentId); CallSetDirectParameters(componentState, parameters); } -#else - static void SetDirectParametersViaComponentState(TestRenderer renderer, int componentId, in ParameterView parameters) - { - var componentState = GetRequiredComponentStateMethod.Invoke(renderer, new object[] { componentId })!; - var setDirectParametersMethod = componentState.GetType().GetMethod("SetDirectParameters", BindingFlags.Public | BindingFlags.Instance)!; - setDirectParametersMethod.Invoke(componentState, new object[] { parameters }); - } -#endif } /// @@ -447,8 +401,7 @@ protected override void Dispose(bool disposing) private TResult Render(RenderFragment renderFragment, Func activator) where TResult : IRenderedFragmentBase { - if (disposed) - throw new ObjectDisposedException(nameof(TestRenderer)); + ObjectDisposedException.ThrowIf(disposed, this); var renderTask = Dispatcher.InvokeAsync(() => { @@ -482,14 +435,12 @@ private TResult Render(RenderFragment renderFragment, Func> FindComponents(IRenderedFragmentBase parentComponent, int resultLimit) + private List> FindComponents(IRenderedFragmentBase parentComponent, int resultLimit) where TComponent : IComponent { - if (parentComponent is null) - throw new ArgumentNullException(nameof(parentComponent)); + ArgumentNullException.ThrowIfNull(parentComponent); - if (disposed) - throw new ObjectDisposedException(nameof(TestRenderer)); + ObjectDisposedException.ThrowIf(disposed, this); var result = new List>(); var framesCollection = new RenderTreeFrameDictionary(); @@ -498,8 +449,7 @@ private IReadOnlyList> FindComponentsFake version of the StringSyntaxAttribute, which was introduced in .NET 7 -[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)] -[SuppressMessage("Design", "CA1019:Define accessors for attribute arguments", Justification = "The sole purpose is to have the same public surface as the class in .NET7 and above.")] -public sealed class StringSyntaxAttribute : Attribute -{ - /// - /// Initializes the with the identifier of the syntax used. - /// - public StringSyntaxAttribute(string syntax) - { - } - - /// - /// Initializes the with the identifier of the syntax used. - /// - public StringSyntaxAttribute(string syntax, params object?[] arguments) - { - } - - /// The syntax identifier for strings containing URIs. - public const string Uri = nameof(Uri); -} -#endif diff --git a/src/bunit.core/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs b/src/bunit.core/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs deleted file mode 100644 index 03049753a..000000000 --- a/src/bunit.core/System.Diagnostics.CodeAnalysis/MemberNotNullAttribute.cs +++ /dev/null @@ -1,29 +0,0 @@ -#if NETSTANDARD2_1 -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -namespace System.Diagnostics.CodeAnalysis; - -/// -/// Specifies that the method or property will ensure that the listed field and property members have not-null values. -/// -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] -internal sealed class MemberNotNullAttribute : Attribute -{ - /// Initializes the attribute with a field or property member. - /// - /// The field or property member that is promised to be not-null. - /// - [SuppressMessage("Design", "CA1019:Define accessors for attribute arguments", Justification = "Copied from dotnet team.")] - public MemberNotNullAttribute(string member) => Members = new[] { member }; - - /// Initializes the attribute with the list of field and property members. - /// - /// The list of field and property members that are promised to be not-null. - /// - public MemberNotNullAttribute(params string[] members) => Members = members; - - /// Gets field or property member names. - public string[] Members { get; } -} -#endif diff --git a/src/bunit.core/TestContextBase.cs b/src/bunit.core/TestContextBase.cs index 9c2fa1e8a..cd660e5f8 100644 --- a/src/bunit.core/TestContextBase.cs +++ b/src/bunit.core/TestContextBase.cs @@ -42,7 +42,6 @@ public abstract class TestContextBase : IDisposable /// public RootRenderTree RenderTree { get; } = new(); -#if NET5_0_OR_GREATER /// /// Gets the . Factories added to it /// will be used to create components during testing, starting with the last added @@ -50,7 +49,6 @@ public abstract class TestContextBase : IDisposable /// then the default Blazor factory is used. /// public ComponentFactoryCollection ComponentFactories { get; } = new(); -#endif /// /// Initializes a new instance of the class. @@ -58,9 +56,7 @@ public abstract class TestContextBase : IDisposable protected TestContextBase() { Services = new TestServiceProvider(); -#if NET5_0_OR_GREATER Services.AddSingleton(_ => ComponentFactories); -#endif } /// diff --git a/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs b/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs index ff69fbf08..d10c717b3 100644 --- a/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs +++ b/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs @@ -1,13 +1,6 @@ -#if NET6_0_OR_GREATER -using System; -using System.Diagnostics.CodeAnalysis; using System.Text.Json; -using System.Threading.Tasks; using Bunit.Rendering; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Infrastructure; -using Microsoft.AspNetCore.Components.RenderTree; -using Microsoft.Extensions.DependencyInjection; namespace Bunit.TestDoubles; @@ -66,8 +59,7 @@ public void TriggerOnPersisting() /// The instance to persist. public void Persist(string key, TValue instance) { - if (key is null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); store.Add(key, JsonSerializer.SerializeToUtf8Bytes(instance, JsonSerializerOptions)); manager.Value.RestoreStateAsync(store); @@ -88,4 +80,3 @@ public void Persist(string key, TValue instance) public bool TryTake(string key, [MaybeNullWhen(false)] out TValue? instance) => manager.Value.State.TryTakeFromJson(key, out instance); } -#endif diff --git a/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs b/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs index b2cd2fa32..15705494a 100644 --- a/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs +++ b/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs @@ -1,9 +1,3 @@ -#if NET6_0_OR_GREATER -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Components; - namespace Bunit.TestDoubles; internal class FakePersistentComponentStateStore : IPersistentComponentStateStore @@ -28,4 +22,3 @@ public Task PersistStateAsync(IReadOnlyDictionary state) return Task.CompletedTask; } } -#endif diff --git a/src/bunit.core/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs b/src/bunit.core/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs index ea5717f5b..2ed1e3dbf 100644 --- a/src/bunit.core/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs +++ b/src/bunit.core/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs @@ -1,8 +1,4 @@ -#if NET6_0_OR_GREATER -using System; -using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Infrastructure; -using Microsoft.Extensions.DependencyInjection; namespace Bunit.TestDoubles; @@ -18,12 +14,10 @@ public static class TestContextBaseExtensions /// The added . public static FakePersistentComponentState AddFakePersistentComponentState(this TestContextBase testContext) { - if (testContext is null) - throw new ArgumentNullException(nameof(testContext)); + ArgumentNullException.ThrowIfNull(testContext); testContext.Services.AddSingleton(); testContext.Services.AddSingleton(s => s.GetRequiredService().State); return new FakePersistentComponentState(testContext.Services); } } -#endif diff --git a/src/bunit.core/TestServiceProvider.cs b/src/bunit.core/TestServiceProvider.cs index f4734786b..9e3054cbd 100644 --- a/src/bunit.core/TestServiceProvider.cs +++ b/src/bunit.core/TestServiceProvider.cs @@ -6,11 +6,7 @@ namespace Bunit; /// Represents a and /// as a single type used for test purposes. /// -#if !NET8_0_OR_GREATER -public sealed class TestServiceProvider : IServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable -#else public sealed class TestServiceProvider : IKeyedServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable -#endif { private static readonly ServiceProviderOptions DefaultServiceProviderOptions = new() { ValidateScopes = true }; private readonly IServiceCollection serviceCollection; @@ -77,10 +73,7 @@ private TestServiceProvider(IServiceCollection initialServiceCollection, bool in /// custom service provider factory public void UseServiceProviderFactory(Func serviceProviderFactory) { - if (serviceProviderFactory is null) - { - throw new ArgumentNullException(nameof(serviceProviderFactory)); - } + ArgumentNullException.ThrowIfNull(serviceProviderFactory); this.serviceProviderFactory = () => serviceProviderFactory(serviceCollection); } @@ -96,10 +89,7 @@ public void UseServiceProviderFactory(Func /// builder configuration action public void UseServiceProviderFactory(IServiceProviderFactory serviceProviderFactory, Action? configure = null) where TContainerBuilder : notnull { - if (serviceProviderFactory is null) - { - throw new ArgumentNullException(nameof(serviceProviderFactory)); - } + ArgumentNullException.ThrowIfNull(serviceProviderFactory); UseServiceProviderFactory(serviceCollection => { @@ -140,16 +130,9 @@ public void AddFallbackServiceProvider(IServiceProvider serviceProvider) /// A service object of type T or null if there is no such service. public TService? GetService() => (TService?)GetService(typeof(TService))!; -#if NETSTANDARD2_1 - /// - [return: MaybeNull] - public object GetService(Type serviceType) - => GetServiceInternal(serviceType); -#else /// public object? GetService(Type serviceType) => GetServiceInternal(serviceType); -#endif private object? GetServiceInternal(Type serviceType) { @@ -234,7 +217,6 @@ public bool Remove(ServiceDescriptor item) return serviceCollection.Remove(item); } -#if NET8_0_OR_GREATER /// public object? GetKeyedService(Type serviceType, object? serviceKey) { @@ -261,7 +243,6 @@ public object GetRequiredKeyedService(Type serviceType, object? serviceKey) return service; } -#endif private void CheckInitializedAndThrow() { diff --git a/src/bunit.core/bunit.core.csproj b/src/bunit.core/bunit.core.csproj index e1e8b2818..f50f7659f 100644 --- a/src/bunit.core/bunit.core.csproj +++ b/src/bunit.core/bunit.core.csproj @@ -1,7 +1,7 @@ - netstandard2.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit Bunit.Core @@ -14,30 +14,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/bunit.generators/Web.Stubs/AttributeStubGenerator/ComponentStubAttribute.cs b/src/bunit.generators/Web.Stubs/AttributeStubGenerator/ComponentStubAttribute.cs index f8c809770..e4ce56393 100644 --- a/src/bunit.generators/Web.Stubs/AttributeStubGenerator/ComponentStubAttribute.cs +++ b/src/bunit.generators/Web.Stubs/AttributeStubGenerator/ComponentStubAttribute.cs @@ -5,7 +5,6 @@ internal static class ComponentStubAttribute public static string ComponentStubAttributeSource = $$""" {{HeaderProvider.Header}} - #if NET5_0_OR_GREATER namespace Bunit; /// @@ -16,6 +15,5 @@ internal sealed class ComponentStubAttribute : global::System.Attribute where T : global::Microsoft.AspNetCore.Components.IComponent { } - #endif """; } diff --git a/src/bunit.web.query/bunit.web.query.csproj b/src/bunit.web.query/bunit.web.query.csproj index 1fedede0d..0fded8cba 100644 --- a/src/bunit.web.query/bunit.web.query.csproj +++ b/src/bunit.web.query/bunit.web.query.csproj @@ -1,7 +1,7 @@ - netstandard2.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit Bunit.Web.Query @@ -14,34 +14,6 @@ - - - - - - all - runtime; build; native; contentfiles; analyzers - - - - - - - - - - - - - - - - - - - - - diff --git a/src/bunit.web/Asserting/CompareToExtensions.cs b/src/bunit.web/Asserting/CompareToExtensions.cs index ca0e7ffe6..bb30c2137 100644 --- a/src/bunit.web/Asserting/CompareToExtensions.cs +++ b/src/bunit.web/Asserting/CompareToExtensions.cs @@ -18,10 +18,8 @@ public static class CompareToExtensions /// Any differences found. public static IReadOnlyList CompareTo(this IRenderedFragment actual, string expected) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var htmlParser = actual.Services.GetRequiredService(); var expectedNodes = htmlParser.Parse(expected); @@ -38,10 +36,8 @@ public static IReadOnlyList CompareTo(this IRenderedFragment actual, stri /// Any differences found. public static IReadOnlyList CompareTo(this IRenderedFragment actual, IRenderedFragment expected) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); return actual.Nodes.CompareTo(expected.Nodes); } @@ -55,10 +51,8 @@ public static IReadOnlyList CompareTo(this IRenderedFragment actual, IRen /// Any differences found. public static IReadOnlyList CompareTo(this INode actual, INodeList expected) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var comparer = actual.GetHtmlComparer(); @@ -74,10 +68,8 @@ public static IReadOnlyList CompareTo(this INode actual, INodeList expect /// Any differences found. public static IReadOnlyList CompareTo(this INodeList actual, INode expected) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var comparer = expected.GetHtmlComparer(); @@ -93,10 +85,8 @@ public static IReadOnlyList CompareTo(this INodeList actual, INode expect /// Any differences found. public static IReadOnlyList CompareTo(this INodeList actual, INodeList expected) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); if (actual.Length == 0 && expected.Length == 0) return Array.Empty(); diff --git a/src/bunit.web/Asserting/DiffAssertExtensions.cs b/src/bunit.web/Asserting/DiffAssertExtensions.cs index 10c473006..6a41a9547 100644 --- a/src/bunit.web/Asserting/DiffAssertExtensions.cs +++ b/src/bunit.web/Asserting/DiffAssertExtensions.cs @@ -16,8 +16,7 @@ public static class DiffAssertExtensions /// The expected single in the collection. public static IDiff ShouldHaveSingleChange(this IEnumerable diffs) { - if (diffs is null) - throw new ArgumentNullException(nameof(diffs)); + ArgumentNullException.ThrowIfNull(diffs); var diffsArray = diffs.ToArray(); @@ -41,10 +40,8 @@ public static IDiff ShouldHaveSingleChange(this IEnumerable diffs) /// The total number of inspectors must exactly match the number of s in the collection. public static void ShouldHaveChanges(this IEnumerable diffs, params Action[] diffInspectors) { - if (diffs is null) - throw new ArgumentNullException(nameof(diffs)); - if (diffInspectors is null) - throw new ArgumentNullException(nameof(diffInspectors)); + ArgumentNullException.ThrowIfNull(diffs); + ArgumentNullException.ThrowIfNull(diffInspectors); var diffsArray = diffs.ToArray(); diff --git a/src/bunit.web/Asserting/FocusAsyncAssertJSInteropExtensions.cs b/src/bunit.web/Asserting/FocusAsyncAssertJSInteropExtensions.cs index cbbba528e..284ee732e 100644 --- a/src/bunit.web/Asserting/FocusAsyncAssertJSInteropExtensions.cs +++ b/src/bunit.web/Asserting/FocusAsyncAssertJSInteropExtensions.cs @@ -1,7 +1,4 @@ -#if NET5_0_OR_GREATER -using System.Collections.Generic; using Bunit.JSInterop.InvocationHandlers.Implementation; -using Microsoft.AspNetCore.Components; namespace Bunit; @@ -29,4 +26,3 @@ public static JSRuntimeInvocation VerifyFocusAsyncInvoke(this BunitJSInterop han public static IReadOnlyList VerifyFocusAsyncInvoke(this BunitJSInterop handler, int calledTimes, string? userMessage = null) => handler.VerifyInvoke(FocusAsyncInvocationHandler.FocusIdentifier, calledTimes, userMessage); } -#endif diff --git a/src/bunit.web/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs b/src/bunit.web/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs index 4e46c1710..c44397d5d 100644 --- a/src/bunit.web/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs +++ b/src/bunit.web/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs @@ -1,5 +1,3 @@ -#if NET6_0_OR_GREATER -using System.Collections.Generic; using Bunit.JSInterop.InvocationHandlers.Implementation; using Microsoft.AspNetCore.Components.Routing; @@ -29,4 +27,3 @@ public static JSRuntimeInvocation VerifyFocusOnNavigateInvoke(this BunitJSIntero public static IReadOnlyList VerifyFocusOnNavigateInvoke(this BunitJSInterop handler, int calledTimes, string? userMessage = null) => handler.VerifyInvoke(FocusOnNavigateHandler.Identifier, calledTimes, userMessage); } -#endif diff --git a/src/bunit.web/Asserting/JSInvokeCountExpectedException.cs b/src/bunit.web/Asserting/JSInvokeCountExpectedException.cs index 856cef937..0e37ec1ee 100644 --- a/src/bunit.web/Asserting/JSInvokeCountExpectedException.cs +++ b/src/bunit.web/Asserting/JSInvokeCountExpectedException.cs @@ -35,21 +35,17 @@ public JSInvokeCountExpectedException(string identifier, int expectedCount, int private JSInvokeCountExpectedException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { - if (serializationInfo is null) - throw new ArgumentNullException(nameof(serializationInfo)); + ArgumentNullException.ThrowIfNull(serializationInfo); ExpectedInvocationCount = serializationInfo.GetInt32(nameof(ExpectedInvocationCount)); ActualInvocationCount = serializationInfo.GetInt32(nameof(ActualInvocationCount)); Identifier = serializationInfo.GetString(nameof(Identifier)) ?? string.Empty; } /// -#if NET8_0_OR_GREATER [Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId = "SYSLIB0051", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] -#endif public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) - throw new ArgumentNullException(nameof(info)); + ArgumentNullException.ThrowIfNull(info); info.AddValue(nameof(ExpectedInvocationCount), ExpectedInvocationCount); info.AddValue(nameof(ActualInvocationCount), ActualInvocationCount); diff --git a/src/bunit.web/Asserting/JSRuntimeAssertExtensions.cs b/src/bunit.web/Asserting/JSRuntimeAssertExtensions.cs index 7bac76a88..de502e0c5 100644 --- a/src/bunit.web/Asserting/JSRuntimeAssertExtensions.cs +++ b/src/bunit.web/Asserting/JSRuntimeAssertExtensions.cs @@ -77,10 +77,8 @@ public static IReadOnlyList VerifyInvoke(this JSRu /// expected targeted element. public static void ShouldBeElementReferenceTo(this object? actualArgument, IElement expectedTargetElement) { - if (actualArgument is null) - throw new ArgumentNullException(nameof(actualArgument)); - if (expectedTargetElement is null) - throw new ArgumentNullException(nameof(expectedTargetElement)); + ArgumentNullException.ThrowIfNull(actualArgument); + ArgumentNullException.ThrowIfNull(expectedTargetElement); if (actualArgument is not ElementReference elmRef) throw new ActualExpectedAssertException(actualArgument.GetType().Name, nameof(ElementReference), "Actual argument type", "Expected argument type", $"The argument was not an {nameof(ElementReference)}"); diff --git a/src/bunit.web/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit.web/Asserting/MarkupMatchesAssertExtensions.cs index a52b1e002..8cb96e004 100644 --- a/src/bunit.web/Asserting/MarkupMatchesAssertExtensions.cs +++ b/src/bunit.web/Asserting/MarkupMatchesAssertExtensions.cs @@ -23,10 +23,8 @@ public static class MarkupMatchesAssertExtensions [AssertionMethod] public static void MarkupMatches([StringSyntax("Html")]this string actual, [StringSyntax("Html")]string expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); using var parser = new BunitHtmlParser(); var actualNodes = parser.Parse(actual); @@ -45,10 +43,8 @@ public static void MarkupMatches([StringSyntax("Html")]this string actual, [Stri [AssertionMethod] public static void MarkupMatches([StringSyntax("Html")]this string actual, IRenderedFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var actualNodes = actual.ToNodeList(expected.Services.GetRequiredService()); actualNodes.MarkupMatches(expected, userMessage); @@ -65,10 +61,8 @@ public static void MarkupMatches([StringSyntax("Html")]this string actual, IRend [AssertionMethod] public static void MarkupMatches([StringSyntax("Html")]this string actual, INodeList expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var actualNodes = actual.ToNodeList(expected.GetHtmlParser()); actualNodes.MarkupMatches(expected, userMessage); @@ -85,10 +79,8 @@ public static void MarkupMatches([StringSyntax("Html")]this string actual, INode [AssertionMethod] public static void MarkupMatches([StringSyntax("Html")]this string actual, INode expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var actualNodes = actual.ToNodeList(expected.GetHtmlParser()); actualNodes.MarkupMatches(expected, userMessage); @@ -105,10 +97,8 @@ public static void MarkupMatches([StringSyntax("Html")]this string actual, INode [AssertionMethod] public static void MarkupMatches(this IRenderedFragment actual, [StringSyntax("Html")]string expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var expectedNodes = expected.ToNodeList(actual.Services.GetRequiredService()); actual.Nodes.MarkupMatches(expectedNodes, userMessage); @@ -125,10 +115,8 @@ public static void MarkupMatches(this IRenderedFragment actual, [StringSyntax("H [AssertionMethod] public static void MarkupMatches(this IRenderedFragment actual, IRenderedFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); actual.Nodes.MarkupMatches(expected.Nodes, userMessage); } @@ -145,10 +133,8 @@ public static void MarkupMatches(this IRenderedFragment actual, IRenderedFragmen [AssertionMethod] public static void MarkupMatches(this INodeList actual, IRenderedFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); actual.MarkupMatches(expected.Nodes, userMessage); } @@ -165,10 +151,8 @@ public static void MarkupMatches(this INodeList actual, IRenderedFragment expect [AssertionMethod] public static void MarkupMatches(this INode actual, IRenderedFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); actual.MarkupMatches(expected.Nodes, userMessage); } @@ -185,10 +169,8 @@ public static void MarkupMatches(this INode actual, IRenderedFragment expected, [AssertionMethod] public static void MarkupMatches(this INode actual, [StringSyntax("Html")]string expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var expectedNodes = expected.ToNodeList(actual.GetHtmlParser()); actual.MarkupMatches(expectedNodes, userMessage); @@ -206,10 +188,8 @@ public static void MarkupMatches(this INode actual, [StringSyntax("Html")]string [AssertionMethod] public static void MarkupMatches(this INodeList actual, [StringSyntax("Html")]string expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var expectedNodes = expected.ToNodeList(actual.GetHtmlParser()); actual.MarkupMatches(expectedNodes, userMessage); @@ -227,10 +207,8 @@ public static void MarkupMatches(this INodeList actual, [StringSyntax("Html")]st [AssertionMethod] public static void MarkupMatches(this INodeList actual, INodeList expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var diffs = actual.CompareTo(expected); @@ -250,10 +228,8 @@ public static void MarkupMatches(this INodeList actual, INodeList expected, stri [AssertionMethod] public static void MarkupMatches(this INodeList actual, INode expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var diffs = actual.CompareTo(expected); @@ -273,10 +249,8 @@ public static void MarkupMatches(this INodeList actual, INode expected, string? [AssertionMethod] public static void MarkupMatches(this INode actual, INodeList expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var diffs = actual.CompareTo(expected); @@ -295,10 +269,8 @@ public static void MarkupMatches(this INode actual, INodeList expected, string? [AssertionMethod] public static void MarkupMatches(this IRenderedFragment actual, RenderFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); // TODO: This will be obsolete with: https://github.com/bUnit-dev/bUnit/issues/1018 // As the renderer would be transient we don't have to new up an instance @@ -321,10 +293,8 @@ public static void MarkupMatches(this IRenderedFragment actual, RenderFragment e [AssertionMethod] public static void MarkupMatches(this INode actual, RenderFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var renderedFragment = actual.GetTestContext()?.RenderInsideRenderTree(expected) as IRenderedFragment ?? AdhocRenderRenderFragment(expected); @@ -342,10 +312,8 @@ public static void MarkupMatches(this INode actual, RenderFragment expected, str [AssertionMethod] public static void MarkupMatches(this INodeList actual, RenderFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var renderedFragment = actual.GetTestContext()?.RenderInsideRenderTree(expected) as IRenderedFragment ?? AdhocRenderRenderFragment(expected); @@ -363,10 +331,8 @@ public static void MarkupMatches(this INodeList actual, RenderFragment expected, [AssertionMethod] public static void MarkupMatches(this IEnumerable actual, [StringSyntax("Html")]string expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); MarkupMatches(actual.ToNodeList(), expected, userMessage); } @@ -382,10 +348,8 @@ public static void MarkupMatches(this IEnumerable actual, [StringSynta [AssertionMethod] public static void MarkupMatches(this IElement actual, IEnumerable expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var expectedNodes = string.Join(string.Empty, expected.Select(e => e.Markup)); @@ -403,10 +367,8 @@ public static void MarkupMatches(this IElement actual, IEnumerable expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var expectedNodes = expected.ToNodeList(); @@ -424,10 +386,8 @@ public static void MarkupMatches(this IElement actual, IEnumerable exp [AssertionMethod] public static void MarkupMatches(this IEnumerable actual, IRenderedFragment expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); MarkupMatches(actual.ToNodeList(), expected, userMessage); } @@ -443,10 +403,8 @@ public static void MarkupMatches(this IEnumerable actual, IRenderedFra [AssertionMethod] public static void MarkupMatches(this IEnumerable actual, IEnumerable expected, string? userMessage = null) { - if (actual is null) - throw new ArgumentNullException(nameof(actual)); - if (expected is null) - throw new ArgumentNullException(nameof(expected)); + ArgumentNullException.ThrowIfNull(actual); + ArgumentNullException.ThrowIfNull(expected); var expectedNodes = string.Join(string.Empty, expected.Select(e => e.Markup)); diff --git a/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs b/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs index 0dd6e2308..bcf8df9ba 100644 --- a/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs +++ b/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs @@ -19,10 +19,8 @@ public static class ShouldBeAdditionAssertExtensions /// A custom user message to display in case the verification fails. public static void ShouldBeAddition(this IDiff actualChange, string expectedChange, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedChange); if (actualChange is not UnexpectedNodeDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Unexpected, "The change was not an addition."); @@ -50,8 +48,7 @@ public static void ShouldBeAddition(this IDiff actualChange, string expectedChan /// A custom user message to display in case the verification fails. public static void ShouldBeAddition(this IDiff actualChange, IRenderedFragment expectedChange, string? userMessage = null) { - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(expectedChange); ShouldBeAddition(actualChange, expectedChange.Nodes, userMessage); } @@ -65,10 +62,8 @@ public static void ShouldBeAddition(this IDiff actualChange, IRenderedFragment e /// A custom user message to display in case the verification fails. public static void ShouldBeAddition(this IDiff actualChange, INodeList expectedChange, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedChange); if (actualChange is not UnexpectedNodeDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Unexpected, "The change was not an addition."); diff --git a/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs b/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs index 9b121dc18..d37cc6f52 100644 --- a/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs +++ b/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs @@ -19,10 +19,8 @@ public static class ShouldBeRemovalAssertExtensions /// A custom user message to display in case the verification fails. public static void ShouldBeRemoval(this IDiff actualChange, string expectedChange, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedChange); if (actualChange is not MissingNodeDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Missing, "The change was not an removal."); @@ -50,8 +48,7 @@ public static void ShouldBeRemoval(this IDiff actualChange, string expectedChang /// A custom user message to display in case the verification fails. public static void ShouldBeRemoval(this IDiff actualChange, IRenderedFragment expectedChange, string? userMessage = null) { - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(expectedChange); ShouldBeRemoval(actualChange, expectedChange.Nodes, userMessage); } @@ -65,10 +62,8 @@ public static void ShouldBeRemoval(this IDiff actualChange, IRenderedFragment ex /// A custom user message to display in case the verification fails. public static void ShouldBeRemoval(this IDiff actualChange, INodeList expectedChange, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedChange); if (actualChange is not MissingNodeDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Missing, "The change was not an removal."); diff --git a/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs b/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs index 395ebc274..da270c64c 100644 --- a/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs +++ b/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs @@ -29,10 +29,8 @@ public static void ShouldHaveSingleTextChange(this IEnumerable diffs, str /// A custom error message to show if the verification fails. public static void ShouldBeTextChange(this IDiff actualChange, string expectedChange, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedChange); if (actualChange is not NodeDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Different, "The change was not a text change."); @@ -57,8 +55,7 @@ public static void ShouldBeTextChange(this IDiff actualChange, string expectedCh /// A custom error message to show if the verification fails. public static void ShouldBeTextChange(this IDiff actualChange, IRenderedFragment expectedChange, string? userMessage = null) { - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(expectedChange); ShouldBeTextChange(actualChange, expectedChange.Nodes, userMessage); } @@ -70,10 +67,8 @@ public static void ShouldBeTextChange(this IDiff actualChange, IRenderedFragment /// A custom error message to show if the verification fails. public static void ShouldBeTextChange(this IDiff actualChange, INodeList expectedChange, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedChange is null) - throw new ArgumentNullException(nameof(expectedChange)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedChange); if (actualChange is not NodeDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Different, "The change was not a text change."); @@ -96,12 +91,9 @@ public static void ShouldBeTextChange(this IDiff actualChange, INodeList expecte /// A custom user message to show when the verification fails. public static void ShouldBeAttributeChange(this IDiff actualChange, string expectedAttrName, string expectedAttrValue, string? userMessage = null) { - if (actualChange is null) - throw new ArgumentNullException(nameof(actualChange)); - if (expectedAttrName is null) - throw new ArgumentNullException(nameof(expectedAttrName)); - if (expectedAttrValue is null) - throw new ArgumentNullException(nameof(expectedAttrValue)); + ArgumentNullException.ThrowIfNull(actualChange); + ArgumentNullException.ThrowIfNull(expectedAttrName); + ArgumentNullException.ThrowIfNull(expectedAttrValue); if (actualChange is not AttrDiff actual) throw new DiffChangeAssertException(actualChange.Result, DiffResult.Different, "The change was not a attribute change."); diff --git a/src/bunit.web/ComponentFactories/StubComponentFactory.cs b/src/bunit.web/ComponentFactories/StubComponentFactory.cs index dc2319845..b7145d751 100644 --- a/src/bunit.web/ComponentFactories/StubComponentFactory.cs +++ b/src/bunit.web/ComponentFactories/StubComponentFactory.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using Bunit.TestDoubles; namespace Bunit.ComponentFactories; @@ -25,4 +24,3 @@ public IComponent Create(Type componentType) return (IComponent)Activator.CreateInstance(typeToCreate, replacementContent)!; } } -#endif diff --git a/src/bunit.web/Diffing/DiffMarkupFormatter.cs b/src/bunit.web/Diffing/DiffMarkupFormatter.cs index ccb033627..e32fc2a36 100644 --- a/src/bunit.web/Diffing/DiffMarkupFormatter.cs +++ b/src/bunit.web/Diffing/DiffMarkupFormatter.cs @@ -37,8 +37,7 @@ public DiffMarkupFormatter() /// protected override string Attribute(IAttr attr) { - if (attr is null) - throw new ArgumentNullException(nameof(attr)); + ArgumentNullException.ThrowIfNull(attr); return Htmlizer.IsBlazorAttribute(attr.Name ?? string.Empty) ? string.Empty diff --git a/src/bunit.web/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs b/src/bunit.web/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs index 6fa6aecc7..37ffa5acf 100644 --- a/src/bunit.web/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs +++ b/src/bunit.web/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs @@ -1,6 +1,3 @@ -#if NET5_0_OR_GREATER -using System; -using System.Threading.Tasks; using AngleSharp.Dom; namespace Bunit; @@ -27,4 +24,3 @@ public static void Toggle(this IElement element) /// A task that completes when the event handler is done. public static Task ToggleAsync(this IElement element, EventArgs eventArgs) => element.TriggerEventAsync("ontoggle", eventArgs); } -#endif diff --git a/src/bunit.web/EventDispatchExtensions/DialogEventDispatchExtensions.cs b/src/bunit.web/EventDispatchExtensions/DialogEventDispatchExtensions.cs index 8dd6f3d7c..8fa2b9706 100644 --- a/src/bunit.web/EventDispatchExtensions/DialogEventDispatchExtensions.cs +++ b/src/bunit.web/EventDispatchExtensions/DialogEventDispatchExtensions.cs @@ -1,6 +1,5 @@ using AngleSharp.Dom; -#if NET8_0_OR_GREATER namespace Bunit; /// @@ -28,4 +27,3 @@ public static class DialogEventDispatchExtensions /// public static Task CloseAsync(this IElement element) => element.TriggerEventAsync("onclose", EventArgs.Empty); } -#endif diff --git a/src/bunit.web/EventDispatchExtensions/MouseEventDispatchExtensions.cs b/src/bunit.web/EventDispatchExtensions/MouseEventDispatchExtensions.cs index 67c7d30a3..d67a0b866 100644 --- a/src/bunit.web/EventDispatchExtensions/MouseEventDispatchExtensions.cs +++ b/src/bunit.web/EventDispatchExtensions/MouseEventDispatchExtensions.cs @@ -252,7 +252,6 @@ public static void MouseUp(this IElement element, MouseEventArgs eventArgs) /// A task that completes when the event handler is done. public static Task MouseUpAsync(this IElement element, MouseEventArgs eventArgs) => element.TriggerEventAsync("onmouseup", eventArgs); -#if NET6_0_OR_GREATER /// /// Raises the @onclick event on , passing the provided /// properties to the event handler via a object. @@ -287,72 +286,6 @@ public static void MouseUp(this IElement element, MouseEventArgs eventArgs) /// Gets or sets the type of the event. public static void Click(this IElement element, long detail = 1, double screenX = default, double screenY = default, double clientX = default, double clientY = default, double pageX = 0, double pageY = 0, double offsetX = 0, double offsetY = 0, long button = default, long buttons = default, bool ctrlKey = default, bool shiftKey = default, bool altKey = default, bool metaKey = default, string? type = default) => _ = ClickAsync(element, new MouseEventArgs { Detail = detail, ScreenX = screenX, ScreenY = screenY, ClientX = clientX, PageX = pageX, PageY = pageY, OffsetX = offsetX, OffsetY = offsetY, ClientY = clientY, Button = button, Buttons = buttons, CtrlKey = ctrlKey, ShiftKey = shiftKey, AltKey = altKey, MetaKey = metaKey, Type = type! }); -#elif NET5_0 - /// - /// Raises the @onclick event on , passing the provided - /// properties to the event handler via a object. - /// - /// The element to raise the event on. - /// A count of consecutive clicks that happened in a short amount of time, incremented by one. - /// The X coordinate of the mouse pointer in global (screen) coordinates. - /// The Y coordinate of the mouse pointer in global (screen) coordinates. - /// The X coordinate of the mouse pointer in local (DOM content) coordinates. - /// The Y coordinate of the mouse pointer in local (DOM content) coordinates. - /// The X coordinate of the mouse pointer in relative (Target Element) coordinates. - /// The Y coordinate of the mouse pointer in relative (Target Element) coordinates. - /// - /// The button number that was pressed when the mouse event was fired: Left button=0, - /// middle button=1 (if present), right button=2. For mice configured for left handed - /// use in which the button actions are reversed the values are instead read from - /// right to left. - /// - /// - /// The buttons being pressed when the mouse event was fired: Left button=1, Right - /// button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, - /// 5th button (typically, "Browser Forward" button)=16. If two or more buttons are - /// pressed, returns the logical sum of the values. E.g., if Left button and Right - /// button are pressed, returns 3 (=1 | 2). - /// - /// true if the control key was down when the event was fired. false otherwise. - /// true if the shift key was down when the event was fired. false otherwise. - /// true if the alt key was down when the event was fired. false otherwise. - /// true if the meta key was down when the event was fired. false otherwise. - /// Gets or sets the type of the event. - public static void Click(this IElement element, long detail = 1, double screenX = default, double screenY = default, double clientX = default, double clientY = default, double offsetX = 0, double offsetY = 0, long button = default, long buttons = default, bool ctrlKey = default, bool shiftKey = default, bool altKey = default, bool metaKey = default, string? type = default) - => _ = ClickAsync(element, new MouseEventArgs { Detail = detail, ScreenX = screenX, ScreenY = screenY, ClientX = clientX, OffsetX = offsetX, OffsetY = offsetY, ClientY = clientY, Button = button, Buttons = buttons, CtrlKey = ctrlKey, ShiftKey = shiftKey, AltKey = altKey, MetaKey = metaKey, Type = type! }); -#else - /// - /// Raises the @onclick event on , passing the provided - /// properties to the event handler via a object. - /// - /// The element to raise the event on. - /// A count of consecutive clicks that happened in a short amount of time, incremented by one. - /// The X coordinate of the mouse pointer in global (screen) coordinates. - /// The Y coordinate of the mouse pointer in global (screen) coordinates. - /// The X coordinate of the mouse pointer in local (DOM content) coordinates. - /// The Y coordinate of the mouse pointer in local (DOM content) coordinates. - /// - /// The button number that was pressed when the mouse event was fired: Left button=0, - /// middle button=1 (if present), right button=2. For mice configured for left handed - /// use in which the button actions are reversed the values are instead read from - /// right to left. - /// - /// - /// The buttons being pressed when the mouse event was fired: Left button=1, Right - /// button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, - /// 5th button (typically, "Browser Forward" button)=16. If two or more buttons are - /// pressed, returns the logical sum of the values. E.g., if Left button and Right - /// button are pressed, returns 3 (=1 | 2). - /// - /// true if the control key was down when the event was fired. false otherwise. - /// true if the shift key was down when the event was fired. false otherwise. - /// true if the alt key was down when the event was fired. false otherwise. - /// true if the meta key was down when the event was fired. false otherwise. - /// Gets or sets the type of the event. - public static void Click(this IElement element, long detail = 1, double screenX = default, double screenY = default, double clientX = default, double clientY = default, long button = default, long buttons = default, bool ctrlKey = default, bool shiftKey = default, bool altKey = default, bool metaKey = default, string? type = default) - => _ = ClickAsync(element, new MouseEventArgs { Detail = detail, ScreenX = screenX, ScreenY = screenY, ClientX = clientX, ClientY = clientY, Button = button, Buttons = buttons, CtrlKey = ctrlKey, ShiftKey = shiftKey, AltKey = altKey, MetaKey = metaKey, Type = type! }); -#endif - /// /// Raises the @onclick event on , passing the provided @@ -372,7 +305,6 @@ public static void Click(this IElement element, MouseEventArgs eventArgs) /// A task that completes when the event handler is done. public static Task ClickAsync(this IElement element, MouseEventArgs eventArgs) => element.TriggerEventAsync("onclick", eventArgs); -#if NET6_0_OR_GREATER /// /// Raises the @ondblclick event on , passing the provided /// properties to the event handler via a object. @@ -407,72 +339,7 @@ public static void Click(this IElement element, MouseEventArgs eventArgs) /// Gets or sets the type of the event. public static void DoubleClick(this IElement element, long detail = 2, double screenX = default, double screenY = default, double clientX = default, double clientY = default, double pageX = 0, double pageY = 0, double offsetX = 0, double offsetY = 0, long button = default, long buttons = default, bool ctrlKey = default, bool shiftKey = default, bool altKey = default, bool metaKey = default, string? type = default) => _ = DoubleClickAsync(element, new MouseEventArgs { Detail = detail, ScreenX = screenX, ScreenY = screenY, ClientX = clientX, ClientY = clientY, PageX = pageX, PageY = pageY, OffsetX = offsetX, OffsetY = offsetY, Button = button, Buttons = buttons, CtrlKey = ctrlKey, ShiftKey = shiftKey, AltKey = altKey, MetaKey = metaKey, Type = type! }); -#elif NET5_0 - /// - /// Raises the @ondblclick event on , passing the provided - /// properties to the event handler via a object. - /// - /// The element to raise the event on. - /// A count of consecutive clicks that happened in a short amount of time, incremented by one. - /// The X coordinate of the mouse pointer in global (screen) coordinates. - /// The Y coordinate of the mouse pointer in global (screen) coordinates. - /// The X coordinate of the mouse pointer in local (DOM content) coordinates. - /// The Y coordinate of the mouse pointer in local (DOM content) coordinates. - /// The X coordinate of the mouse pointer in relative (Target Element) coordinates. - /// The Y coordinate of the mouse pointer in relative (Target Element) coordinates. - /// - /// The button number that was pressed when the mouse event was fired: Left button=0, - /// middle button=1 (if present), right button=2. For mice configured for left handed - /// use in which the button actions are reversed the values are instead read from - /// right to left. - /// - /// - /// The buttons being pressed when the mouse event was fired: Left button=1, Right - /// button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, - /// 5th button (typically, "Browser Forward" button)=16. If two or more buttons are - /// pressed, returns the logical sum of the values. E.g., if Left button and Right - /// button are pressed, returns 3 (=1 | 2). - /// - /// true if the control key was down when the event was fired. false otherwise. - /// true if the shift key was down when the event was fired. false otherwise. - /// true if the alt key was down when the event was fired. false otherwise. - /// true if the meta key was down when the event was fired. false otherwise. - /// Gets or sets the type of the event. - public static void DoubleClick(this IElement element, long detail = 2, double screenX = default, double screenY = default, double clientX = default, double clientY = default, double offsetX = 0, double offsetY = 0, long button = default, long buttons = default, bool ctrlKey = default, bool shiftKey = default, bool altKey = default, bool metaKey = default, string? type = default) - => _ = DoubleClickAsync(element, new MouseEventArgs { Detail = detail, ScreenX = screenX, ScreenY = screenY, ClientX = clientX, ClientY = clientY, OffsetX = offsetX, OffsetY = offsetY, Button = button, Buttons = buttons, CtrlKey = ctrlKey, ShiftKey = shiftKey, AltKey = altKey, MetaKey = metaKey, Type = type! }); -#else - /// - /// Raises the @ondblclick event on , passing the provided - /// properties to the event handler via a object. - /// - /// The element to raise the event on. - /// A count of consecutive clicks that happened in a short amount of time, incremented by one. - /// The X coordinate of the mouse pointer in global (screen) coordinates. - /// The Y coordinate of the mouse pointer in global (screen) coordinates. - /// The X coordinate of the mouse pointer in local (DOM content) coordinates. - /// The Y coordinate of the mouse pointer in local (DOM content) coordinates. - /// - /// The button number that was pressed when the mouse event was fired: Left button=0, - /// middle button=1 (if present), right button=2. For mice configured for left handed - /// use in which the button actions are reversed the values are instead read from - /// right to left. - /// - /// - /// The buttons being pressed when the mouse event was fired: Left button=1, Right - /// button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, - /// 5th button (typically, "Browser Forward" button)=16. If two or more buttons are - /// pressed, returns the logical sum of the values. E.g., if Left button and Right - /// button are pressed, returns 3 (=1 | 2). - /// - /// true if the control key was down when the event was fired. false otherwise. - /// true if the shift key was down when the event was fired. false otherwise. - /// true if the alt key was down when the event was fired. false otherwise. - /// true if the meta key was down when the event was fired. false otherwise. - /// Gets or sets the type of the event. - public static void DoubleClick(this IElement element, long detail = 2, double screenX = default, double screenY = default, double clientX = default, double clientY = default, long button = default, long buttons = default, bool ctrlKey = default, bool shiftKey = default, bool altKey = default, bool metaKey = default, string? type = default) - => _ = DoubleClickAsync(element, new MouseEventArgs { Detail = detail, ScreenX = screenX, ScreenY = screenY, ClientX = clientX, ClientY = clientY, Button = button, Buttons = buttons, CtrlKey = ctrlKey, ShiftKey = shiftKey, AltKey = altKey, MetaKey = metaKey, Type = type! }); -#endif /// /// Raises the @ondblclick event on , passing the provided /// to the event handler. diff --git a/src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs b/src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs index 410072f34..2a243b8b1 100644 --- a/src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs +++ b/src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs @@ -59,15 +59,8 @@ public static void TriggerEvent(this IElement element, string eventName, EventAr /// A that completes when the render caused by the triggering of the event finishes. public static Task TriggerEventAsync(this IElement element, string eventName, EventArgs eventArgs) { - if (element is null) - { - throw new ArgumentNullException(nameof(element)); - } - - if (eventName is null) - { - throw new ArgumentNullException(nameof(eventName)); - } + ArgumentNullException.ThrowIfNull(element); + ArgumentNullException.ThrowIfNull(eventName); var renderer = element.GetTestContext()?.Renderer ?? throw new InvalidOperationException($"Blazor events can only be raised on elements rendered with the Blazor test renderer '{nameof(ITestRenderer)}'."); diff --git a/src/bunit.web/Extensions/ElementNotFoundException.cs b/src/bunit.web/Extensions/ElementNotFoundException.cs index 8d6d46af3..ea4ce0949 100644 --- a/src/bunit.web/Extensions/ElementNotFoundException.cs +++ b/src/bunit.web/Extensions/ElementNotFoundException.cs @@ -40,13 +40,10 @@ protected ElementNotFoundException(SerializationInfo serializationInfo, Streamin } /// -#if NET8_0_OR_GREATER [Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId = "SYSLIB0051", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] -#endif public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) - throw new ArgumentNullException(nameof(info)); + ArgumentNullException.ThrowIfNull(info); info.AddValue(nameof(CssSelector), CssSelector); base.GetObjectData(info, context); } diff --git a/src/bunit.web/Extensions/InputFile/BUnitBrowserFile.cs b/src/bunit.web/Extensions/InputFile/BUnitBrowserFile.cs index a50a89176..7ee64d03b 100644 --- a/src/bunit.web/Extensions/InputFile/BUnitBrowserFile.cs +++ b/src/bunit.web/Extensions/InputFile/BUnitBrowserFile.cs @@ -1,5 +1,4 @@ -#if NET5_0_OR_GREATER -using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Components.Forms; namespace Bunit; @@ -35,4 +34,3 @@ public Stream OpenReadStream(long maxAllowedSize = 512000, CancellationToken can return new MemoryStream(Content); } } -#endif diff --git a/src/bunit.web/Extensions/InputFile/InputFileContent.cs b/src/bunit.web/Extensions/InputFile/InputFileContent.cs index 6427e4bdf..1c45ab5a7 100644 --- a/src/bunit.web/Extensions/InputFile/InputFileContent.cs +++ b/src/bunit.web/Extensions/InputFile/InputFileContent.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using System.Text; namespace Bunit; @@ -39,8 +38,7 @@ public static InputFileContent CreateFromText( DateTimeOffset? lastChanged = null, string? contentType = null) { - if (fileContent == null) - throw new ArgumentNullException(nameof(fileContent)); + ArgumentNullException.ThrowIfNull(fileContent); return new InputFileContent(Encoding.Default.GetBytes(fileContent), fileName, lastChanged, contentType); } @@ -58,10 +56,8 @@ public static InputFileContent CreateFromBinary( DateTimeOffset? lastChanged = null, string? contentType = null) { - if (fileContent == null) - throw new ArgumentNullException(nameof(fileContent)); + ArgumentNullException.ThrowIfNull(fileContent); return new InputFileContent(fileContent, fileName, lastChanged, contentType); } } -#endif \ No newline at end of file diff --git a/src/bunit.web/Extensions/InputFile/InputFileExtensions.cs b/src/bunit.web/Extensions/InputFile/InputFileExtensions.cs index 39c6d7395..c9cb111e7 100644 --- a/src/bunit.web/Extensions/InputFile/InputFileExtensions.cs +++ b/src/bunit.web/Extensions/InputFile/InputFileExtensions.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using System.Runtime.ExceptionServices; using Microsoft.AspNetCore.Components.Forms; @@ -18,11 +17,9 @@ public static void UploadFiles( this IRenderedComponent inputFileComponent, params InputFileContent[] files) { - if (inputFileComponent == null) - throw new ArgumentNullException(nameof(inputFileComponent)); - - if (!files.Any()) - throw new ArgumentException("No files were provided to be uploaded.", nameof(files)); + ArgumentNullException.ThrowIfNull(inputFileComponent); + ArgumentNullException.ThrowIfNull(files); + ArgumentOutOfRangeException.ThrowIfZero(files.Length); var browserFiles = files.Select(file => new BUnitBrowserFile( file.Filename ?? string.Empty, @@ -44,4 +41,3 @@ public static void UploadFiles( } } } -#endif diff --git a/src/bunit.web/Extensions/NodePrintExtensions.cs b/src/bunit.web/Extensions/NodePrintExtensions.cs index c54924824..b21f5eabf 100644 --- a/src/bunit.web/Extensions/NodePrintExtensions.cs +++ b/src/bunit.web/Extensions/NodePrintExtensions.cs @@ -20,8 +20,7 @@ public static class NodePrintExtensions /// The formatter to use. public static void ToHtml(this IEnumerable nodes, TextWriter writer, IMarkupFormatter formatter) { - if (nodes is null) - throw new ArgumentNullException(nameof(nodes)); + ArgumentNullException.ThrowIfNull(nodes); foreach (var node in nodes) { @@ -37,8 +36,7 @@ public static void ToHtml(this IEnumerable nodes, TextWriter writer, IMar /// public static string ToDiffMarkup(this IEnumerable nodes) { - if (nodes is null) - throw new ArgumentNullException(nameof(nodes)); + ArgumentNullException.ThrowIfNull(nodes); using var sw = new StringWriter(); nodes.ToHtml(sw, new DiffMarkupFormatter()); @@ -53,8 +51,7 @@ public static string ToDiffMarkup(this IEnumerable nodes) /// public static string ToDiffMarkup(this IMarkupFormattable markupFormattable) { - if (markupFormattable is null) - throw new ArgumentNullException(nameof(markupFormattable)); + ArgumentNullException.ThrowIfNull(markupFormattable); using var sw = new StringWriter(); markupFormattable.ToHtml(sw, new DiffMarkupFormatter()); @@ -67,8 +64,7 @@ public static string ToDiffMarkup(this IMarkupFormattable markupFormattable) /// public static string ToMarkup(this IEnumerable nodes) { - if (nodes is null) - throw new ArgumentNullException(nameof(nodes)); + ArgumentNullException.ThrowIfNull(nodes); using var sw = new StringWriter(); var formatter = new PrettyMarkupFormatter @@ -86,8 +82,7 @@ public static string ToMarkup(this IEnumerable nodes) /// public static string ToMarkup(this IMarkupFormattable markupFormattable) { - if (markupFormattable is null) - throw new ArgumentNullException(nameof(markupFormattable)); + ArgumentNullException.ThrowIfNull(markupFormattable); using var sw = new StringWriter(); var formatter = new PrettyMarkupFormatter @@ -106,8 +101,7 @@ public static string ToMarkup(this IMarkupFormattable markupFormattable) /// public static string ToMarkupElementOnly(this IElement element) { - if (element is null) - throw new ArgumentNullException(nameof(element)); + ArgumentNullException.ThrowIfNull(element); var result = new StringBuilder(); result.Append(Symbols.LessThan); diff --git a/src/bunit.web/Extensions/RenderedFragmentExtensions.cs b/src/bunit.web/Extensions/RenderedFragmentExtensions.cs index 7c0da6a25..af888b3f2 100644 --- a/src/bunit.web/Extensions/RenderedFragmentExtensions.cs +++ b/src/bunit.web/Extensions/RenderedFragmentExtensions.cs @@ -18,8 +18,7 @@ public static class RenderedFragmentExtensions /// The group of selectors to use. public static IElement Find(this IRenderedFragment renderedFragment, string cssSelector) { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); var result = renderedFragment.Nodes.QuerySelector(cssSelector); @@ -40,8 +39,7 @@ public static IElement Find(this IRenderedFragment renderedFragment, string cssS /// An , that can be refreshed to execute the search again. public static IRefreshableElementCollection FindAll(this IRenderedFragment renderedFragment, string cssSelector, bool enableAutoRefresh = false) { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); return new RefreshableElementCollection(renderedFragment, cssSelector) { EnableAutoRefresh = enableAutoRefresh }; } @@ -55,8 +53,7 @@ public static IRefreshableElementCollection FindAll(this IRenderedFrag public static IRenderedComponent FindComponent(this IRenderedFragment renderedFragment) where TComponent : IComponent { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); var renderer = renderedFragment.Services.GetRequiredService().Renderer; return (IRenderedComponent)renderer.FindComponent(renderedFragment); @@ -71,8 +68,7 @@ public static IRenderedComponent FindComponent(this IRen public static IReadOnlyList> FindComponents(this IRenderedFragment renderedFragment) where TComponent : IComponent { - if (renderedFragment is null) - throw new ArgumentNullException(nameof(renderedFragment)); + ArgumentNullException.ThrowIfNull(renderedFragment); var renderer = renderedFragment.Services.GetRequiredService().Renderer; var components = renderer.FindComponents(renderedFragment); diff --git a/src/bunit.web/Extensions/StubComponentFactoryCollectionExtensions.cs b/src/bunit.web/Extensions/StubComponentFactoryCollectionExtensions.cs index 011c82464..6a17b8ec1 100644 --- a/src/bunit.web/Extensions/StubComponentFactoryCollectionExtensions.cs +++ b/src/bunit.web/Extensions/StubComponentFactoryCollectionExtensions.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using Bunit.ComponentFactories; using Bunit.TestDoubles; @@ -19,8 +18,7 @@ public static class StubComponentFactoryCollectionExtensions /// A . public static ComponentFactoryCollection AddStub(this ComponentFactoryCollection factories) where TComponent : IComponent { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); + ArgumentNullException.ThrowIfNull(factories); factories.Add(new StubComponentFactory(CreatePredicate(typeof(TComponent)), null)); @@ -53,8 +51,7 @@ public static ComponentFactoryCollection AddStub(this ComponentFacto /// A . public static ComponentFactoryCollection AddStub(this ComponentFactoryCollection factories, RenderFragment replacementFragment) where TComponent : IComponent { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); + ArgumentNullException.ThrowIfNull(factories); factories.Add(new StubComponentFactory(CreatePredicate(typeof(TComponent)), replacementFragment)); @@ -95,10 +92,8 @@ public static ComponentFactoryCollection AddStub( RenderFragment> replacementTemplate) where TComponent : IComponent { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); - if (replacementTemplate is null) - throw new ArgumentNullException(nameof(replacementTemplate)); + ArgumentNullException.ThrowIfNull(factories); + ArgumentNullException.ThrowIfNull(replacementTemplate); factories.Add(new StubComponentFactory(CreatePredicate(typeof(TComponent)), replacementTemplate)); @@ -153,13 +148,10 @@ public static ComponentFactoryCollection AddStub( Predicate componentTypePredicate, RenderFragment replacementFragment) { - if (factories is null) - throw new ArgumentNullException(nameof(factories)); - if (componentTypePredicate is null) - throw new ArgumentNullException(nameof(componentTypePredicate)); + ArgumentNullException.ThrowIfNull(factories); + ArgumentNullException.ThrowIfNull(componentTypePredicate); factories.Add(new StubComponentFactory(componentTypePredicate, replacementFragment)); return factories; } } -#endif diff --git a/src/bunit.web/Extensions/TestRendererExtensions.cs b/src/bunit.web/Extensions/TestRendererExtensions.cs index 14b4965c3..d1b6243a5 100644 --- a/src/bunit.web/Extensions/TestRendererExtensions.cs +++ b/src/bunit.web/Extensions/TestRendererExtensions.cs @@ -18,8 +18,7 @@ public static class TestRendererExtensions public static IRenderedComponent RenderComponent(this ITestRenderer renderer, params ComponentParameter[] parameters) where TComponent : IComponent { - if (renderer is null) - throw new ArgumentNullException(nameof(renderer)); + ArgumentNullException.ThrowIfNull(renderer); var resultBase = renderer.RenderComponent(new ComponentParameterCollection { parameters }); if (resultBase is IRenderedComponent result) @@ -38,10 +37,8 @@ public static IRenderedComponent RenderComponent(this IT public static IRenderedComponent RenderComponent(this ITestRenderer renderer, Action> parameterBuilder) where TComponent : IComponent { - if (renderer is null) - throw new ArgumentNullException(nameof(renderer)); - if (parameterBuilder is null) - throw new ArgumentNullException(nameof(parameterBuilder)); + ArgumentNullException.ThrowIfNull(renderer); + ArgumentNullException.ThrowIfNull(parameterBuilder); var builder = new ComponentParameterCollectionBuilder(parameterBuilder); var resultBase = renderer.RenderComponent(builder.Build()); diff --git a/src/bunit.web/Extensions/TestServiceProviderExtensions.cs b/src/bunit.web/Extensions/TestServiceProviderExtensions.cs index e23f5b002..c93faa0ec 100644 --- a/src/bunit.web/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit.web/Extensions/TestServiceProviderExtensions.cs @@ -19,12 +19,9 @@ public static class TestServiceProviderExtensions /// public static IServiceCollection AddDefaultTestContextServices(this IServiceCollection services, TestContextBase testContext, BunitJSInterop jsInterop) { - if (services is null) - throw new System.ArgumentNullException(nameof(services)); - if (testContext is null) - throw new System.ArgumentNullException(nameof(testContext)); - if (jsInterop is null) - throw new System.ArgumentNullException(nameof(jsInterop)); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(testContext); + ArgumentNullException.ThrowIfNull(jsInterop); // Placeholders and defaults for common Blazor services services.AddLogging(); @@ -45,11 +42,9 @@ public static IServiceCollection AddDefaultTestContextServices(this IServiceColl services.AddSingleton(); services.AddSingleton(s => s.GetRequiredService()); -#if NET8_0_OR_GREATER // bUnits fake ScrollToLocationHash services.AddSingleton(); services.AddSupplyValueFromQueryProvider(); -#endif // bUnit specific services services.AddSingleton(testContext); @@ -59,9 +54,7 @@ public static IServiceCollection AddDefaultTestContextServices(this IServiceColl services.AddMemoryCache(); -#if NET6_0_OR_GREATER services.AddSingleton(); -#endif return services; } } diff --git a/src/bunit.web/Extensions/WaitForHelpers/WaitForElementsHelper.cs b/src/bunit.web/Extensions/WaitForHelpers/WaitForElementsHelper.cs index bde317a68..179fdec55 100644 --- a/src/bunit.web/Extensions/WaitForHelpers/WaitForElementsHelper.cs +++ b/src/bunit.web/Extensions/WaitForHelpers/WaitForElementsHelper.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text; using AngleSharp.Dom; namespace Bunit.Extensions.WaitForHelpers; @@ -9,7 +10,7 @@ namespace Bunit.Extensions.WaitForHelpers; internal class WaitForElementsHelper : WaitForHelper> { internal const string TimeoutBeforeFoundMessage = "The CSS selector did not result in any matching element(s) before the timeout period passed."; - internal const string TimeoutBeforeFoundWithCountMessage = "The CSS selector did not result in exactly {0} matching element(s) before the timeout period passed."; + internal static readonly CompositeFormat TimeoutBeforeFoundWithCountMessage = CompositeFormat.Parse("The CSS selector did not result in exactly {0} matching element(s) before the timeout period passed."); private readonly int? matchElementCount; /// diff --git a/src/bunit.web/JSInterop/BunitJSInterop.cs b/src/bunit.web/JSInterop/BunitJSInterop.cs index 4c15f4a65..2dbaa9787 100644 --- a/src/bunit.web/JSInterop/BunitJSInterop.cs +++ b/src/bunit.web/JSInterop/BunitJSInterop.cs @@ -1,8 +1,5 @@ using Bunit.JSInterop; - -#if NET5_0_OR_GREATER using Bunit.JSInterop.InvocationHandlers.Implementation; -#endif namespace Bunit; @@ -37,12 +34,7 @@ public BunitJSInterop() { mode = JSRuntimeMode.Strict; JSRuntime = new BunitJSRuntime(this); -#if NET5_0_OR_GREATER - AddCustomNet5Handlers(); -#endif -#if NET6_0_OR_GREATER - AddCustomNet6Handlers(); -#endif + AddCustomHandlers(); } /// @@ -51,8 +43,7 @@ public BunitJSInterop() /// public void AddInvocationHandler(JSRuntimeInvocationHandlerBase handler) { - if (handler is null) - throw new ArgumentNullException(nameof(handler)); + ArgumentNullException.ThrowIfNull(handler); var resultType = typeof(TResult); @@ -129,24 +120,14 @@ internal virtual void RegisterInvocation(JSRuntimeInvocation invocation) return default; } -#if NET5_0_OR_GREATER - private void AddCustomNet5Handlers() + private void AddCustomHandlers() { AddInvocationHandler(new FocusAsyncInvocationHandler()); AddInvocationHandler(new VirtualizeJSRuntimeInvocationHandler()); AddInvocationHandler(new LooseModeJSObjectReferenceInvocationHandler(this)); AddInvocationHandler(new InputFileInvocationHandler()); - } -#endif - -#if NET6_0_OR_GREATER - private void AddCustomNet6Handlers() - { AddInvocationHandler(new FocusOnNavigateHandler()); -#if NET7_0_OR_GREATER AddInvocationHandler(new NavigationLockDisableNavigationPromptInvocationHandler()); AddInvocationHandler(new NavigationLockEnableNavigationPromptInvocationHandler()); -#endif } -#endif -} \ No newline at end of file +} diff --git a/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.cs b/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.cs index 1044d829b..7cc5059f6 100644 --- a/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.cs +++ b/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.cs @@ -16,12 +16,9 @@ public static partial class BunitJSInteropSetupExtensions /// A . public static JSRuntimeInvocationHandler Setup(this BunitJSInterop jsInterop, InvocationMatcher invocationMatcher, bool isCatchAllHandler = false) { - if (jsInterop is null) - throw new ArgumentNullException(nameof(jsInterop)); + ArgumentNullException.ThrowIfNull(jsInterop); -#if NET5_0_OR_GREATER EnsureResultNotIJSObjectReference(); -#endif var result = new JSRuntimeInvocationHandler(invocationMatcher, isCatchAllHandler); jsInterop.AddInvocationHandler(result); @@ -72,8 +69,7 @@ public static JSRuntimeInvocationHandler Setup(this BunitJSInt /// A . public static JSRuntimeInvocationHandler SetupVoid(this BunitJSInterop jsInterop, InvocationMatcher invocationMatcher, bool isCatchAllHandler = false) { - if (jsInterop is null) - throw new ArgumentNullException(nameof(jsInterop)); + ArgumentNullException.ThrowIfNull(jsInterop); var result = new JSRuntimeInvocationHandler(invocationMatcher, isCatchAllHandler); jsInterop.AddInvocationHandler(result); @@ -122,8 +118,7 @@ public static JSRuntimeInvocationHandler SetupVoid(this BunitJSInterop jsInterop /// Returns the or null if no one is found. public static JSRuntimeInvocationHandler? TryGetInvokeHandler(this BunitJSInterop jsInterop, string identifier, params object?[]? arguments) { - if (jsInterop is null) - throw new ArgumentNullException(nameof(jsInterop)); + ArgumentNullException.ThrowIfNull(jsInterop); return jsInterop.TryGetHandlerFor( new JSRuntimeInvocation( @@ -144,19 +139,13 @@ public static JSRuntimeInvocationHandler SetupVoid(this BunitJSInterop jsInterop /// Returns the or null if no one is found. public static JSRuntimeInvocationHandler? TryGetInvokeVoidHandler(this BunitJSInterop jsInterop, string identifier, params object?[]? arguments) { - if (jsInterop is null) - throw new ArgumentNullException(nameof(jsInterop)); + ArgumentNullException.ThrowIfNull(jsInterop); var invocation = new JSRuntimeInvocation(identifier, default, arguments, typeof(object), string.Empty); -#if !NET6_0_OR_GREATER - return jsInterop.TryGetHandlerFor(invocation, x => x.IsVoidResultHandler) as JSRuntimeInvocationHandler; -#else return jsInterop.TryGetHandlerFor(invocation, x => x.IsVoidResultHandler) as JSRuntimeInvocationHandler; -#endif } -#if NET5_0_OR_GREATER private static void EnsureResultNotIJSObjectReference() { const string UseSetupModuleErrorMessage = "Use one of the SetupModule() methods instead to set up an invocation handler that returns an IJSObjectReference."; @@ -169,5 +158,4 @@ private static void EnsureResultNotIJSObjectReference() if (resultType == typeof(Microsoft.JSInterop.Implementation.JSObjectReference)) throw new ArgumentException(UseSetupModuleErrorMessage); } -#endif } diff --git a/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.net5.cs b/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.net5.cs index 8487570b6..ebf393656 100644 --- a/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.net5.cs +++ b/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.net5.cs @@ -1,11 +1,4 @@ -#if NET5_0_OR_GREATER -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using Bunit.JSInterop; -using Bunit.JSInterop.InvocationHandlers; using Bunit.JSInterop.InvocationHandlers.Implementation; -using Microsoft.JSInterop; namespace Bunit; @@ -33,10 +26,8 @@ public static partial class BunitJSInteropSetupExtensions /// A . public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, InvocationMatcher invocationMatcher, bool isCatchAllHandler = false) { - if (jsInterop is null) - throw new ArgumentNullException(nameof(jsInterop)); - if (invocationMatcher is null) - throw new ArgumentNullException(nameof(invocationMatcher)); + ArgumentNullException.ThrowIfNull(jsInterop); + ArgumentNullException.ThrowIfNull(invocationMatcher); var result = new JSObjectReferenceInvocationHandler(jsInterop, invocationMatcher, isCatchAllHandler); jsInterop.AddInvocationHandler(result); @@ -131,8 +122,7 @@ public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop) /// A or null if no one is found. public static BunitJSModuleInterop? TryGetModuleJSInterop(this BunitJSInterop jsInterop, string identifier, params object?[]? arguments) { - if (jsInterop is null) - throw new ArgumentNullException(nameof(jsInterop)); + ArgumentNullException.ThrowIfNull(jsInterop); var invocation = new JSRuntimeInvocation(identifier, default, arguments, typeof(IJSObjectReference), "InvokeAsync"); @@ -141,4 +131,3 @@ public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop) return handler?.JSInterop; } } -#endif diff --git a/src/bunit.web/JSInterop/BunitJSModuleInterop.cs b/src/bunit.web/JSInterop/BunitJSModuleInterop.cs index ca5746844..292df5eeb 100644 --- a/src/bunit.web/JSInterop/BunitJSModuleInterop.cs +++ b/src/bunit.web/JSInterop/BunitJSModuleInterop.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit; /// @@ -44,4 +43,3 @@ internal override void RegisterInvocation(JSRuntimeInvocation invocation) parent.RegisterInvocation(invocation); } } -#endif diff --git a/src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs b/src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs index 49ab896a1..aaaf19ede 100644 --- a/src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs +++ b/src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs @@ -1,10 +1,4 @@ -#if NET5_0_OR_GREATER -using System; -using System.Diagnostics.CodeAnalysis; -using System.Threading; -using System.Threading.Tasks; using Bunit.JSInterop.Implementation; -using Microsoft.JSInterop; namespace Bunit; @@ -58,4 +52,3 @@ public void Dispose() /// public ValueTask DisposeAsync() => ValueTask.CompletedTask; } -#endif diff --git a/src/bunit.web/JSInterop/Implementation/BunitJSRuntime.net5.cs b/src/bunit.web/JSInterop/Implementation/BunitJSRuntime.net5.cs index f2f466d58..1a3a8d649 100644 --- a/src/bunit.web/JSInterop/Implementation/BunitJSRuntime.net5.cs +++ b/src/bunit.web/JSInterop/Implementation/BunitJSRuntime.net5.cs @@ -1,7 +1,5 @@ -#if NET5_0_OR_GREATER && !NET9_0_OR_GREATER -using System; +#if !NET9_0_OR_GREATER using Bunit.JSInterop.Implementation; -using Microsoft.JSInterop; namespace Bunit.JSInterop; diff --git a/src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs b/src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs index e29a37330..2490e4bc6 100644 --- a/src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs +++ b/src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs @@ -85,27 +85,13 @@ internal static TResult HandleInvokeUnmarshalled(this Bunit .GetResult(); } -#if !NET6_0_OR_GREATER - private static string GetInvokeAsyncMethodName() - => typeof(TValue) == typeof(object) - ? "InvokeVoidAsync" - : "InvokeAsync"; -#else private static string GetInvokeAsyncMethodName() => typeof(TValue) == typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult) ? "InvokeVoidAsync" : "InvokeAsync"; -#endif -#if !NET6_0_OR_GREATER - private static string GetInvokeMethodName() - => typeof(TValue) == typeof(object) - ? "InvokeVoid" - : "Invoke"; -#else private static string GetInvokeMethodName() => typeof(TValue) == typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult) ? "InvokeVoid" : "Invoke"; -#endif } diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs index 1beae3348..26813499d 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs @@ -1,8 +1,3 @@ - -#if NET5_0_OR_GREATER -using System; -using Microsoft.AspNetCore.Components; - namespace Bunit.JSInterop.InvocationHandlers.Implementation; /// @@ -26,4 +21,3 @@ internal FocusAsyncInvocationHandler() SetVoidResult(); } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs index 260326c0c..33795b8b7 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs @@ -1,6 +1,3 @@ -#if NET6_0_OR_GREATER -using System; -using Microsoft.AspNetCore.Components; namespace Bunit.JSInterop.InvocationHandlers.Implementation; /// @@ -24,4 +21,3 @@ internal FocusOnNavigateHandler() SetVoidResult(); } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs index 85f0971a8..f2cd98cd8 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs @@ -1,5 +1,4 @@ -#if NET5_0_OR_GREATER -namespace Bunit.JSInterop.InvocationHandlers.Implementation; +namespace Bunit.JSInterop.InvocationHandlers.Implementation; internal sealed class InputFileInvocationHandler : JSRuntimeInvocationHandler { @@ -11,4 +10,3 @@ internal InputFileInvocationHandler() SetVoidResult(); } } -#endif \ No newline at end of file diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs index b824ed9c5..83d0424c7 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - namespace Bunit.JSInterop.InvocationHandlers.Implementation; /// @@ -25,4 +23,3 @@ public JSObjectReferenceInvocationHandler(BunitJSInterop parent, InvocationMatch SetResult(new BunitJSObjectReference(JSInterop)); } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs index 356257b3a..7ff86b7fc 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - namespace Bunit.JSInterop.InvocationHandlers.Implementation; /// @@ -15,4 +13,3 @@ internal LooseModeJSObjectReferenceInvocationHandler(BunitJSInterop parent) SetResult(new BunitJSObjectReference(parent)); } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs index f1740d2ce..f80d3a60c 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs @@ -1,4 +1,3 @@ -#if NET7_0_OR_GREATER namespace Bunit.JSInterop.InvocationHandlers.Implementation; internal sealed class NavigationLockDisableNavigationPromptInvocationHandler : JSRuntimeInvocationHandler @@ -11,4 +10,3 @@ internal NavigationLockDisableNavigationPromptInvocationHandler() SetVoidResult(); } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs index c5015288e..a4df314ec 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs @@ -1,4 +1,3 @@ -#if NET7_0_OR_GREATER namespace Bunit.JSInterop.InvocationHandlers.Implementation; internal sealed class NavigationLockEnableNavigationPromptInvocationHandler : JSRuntimeInvocationHandler @@ -11,4 +10,3 @@ internal NavigationLockEnableNavigationPromptInvocationHandler() SetVoidResult(); } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs index 59c80ac56..97814aed3 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs @@ -1,11 +1,6 @@ -#if NET5_0_OR_GREATER -using System; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.Reflection; -using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Web.Virtualization; -using Microsoft.JSInterop; namespace Bunit.JSInterop.InvocationHandlers.Implementation { @@ -38,11 +33,7 @@ internal VirtualizeJSRuntimeInvocationHandler() { } /// -#if !NET6_0_OR_GREATER - protected internal override Task HandleAsync(JSRuntimeInvocation invocation) -#else protected internal override Task HandleAsync(JSRuntimeInvocation invocation) -#endif { if (!invocation.Identifier.Equals(JsFunctionsPrefix + "dispose", StringComparison.Ordinal)) { @@ -73,4 +64,3 @@ private static void InvokeOnSpacerBeforeVisible(object dotNetObjectReference) } } } -#endif diff --git a/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs b/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs index 2c7e0f888..7d2cc5a26 100644 --- a/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs +++ b/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs @@ -4,11 +4,7 @@ namespace Bunit; /// Represents a handler for an invocation of a JavaScript function which returns nothing, with specific arguments. /// public class JSRuntimeInvocationHandler -#if !NET6_0_OR_GREATER - : JSRuntimeInvocationHandlerBase -#else : JSRuntimeInvocationHandlerBase -#endif { /// public override sealed bool IsVoidResultHandler => true; diff --git a/src/bunit.web/JSInterop/JSRuntimeInvocation.cs b/src/bunit.web/JSInterop/JSRuntimeInvocation.cs index d30350a2d..ca7ea33c1 100644 --- a/src/bunit.web/JSInterop/JSRuntimeInvocation.cs +++ b/src/bunit.web/JSInterop/JSRuntimeInvocation.cs @@ -66,11 +66,7 @@ public JSRuntimeInvocation( Arguments = args ?? Array.Empty(); ResultType = resultType; InvocationMethodName = invocationMethodName; -#if !NET6_0_OR_GREATER - IsVoidResultInvocation = resultType == typeof(object); -#else IsVoidResultInvocation = resultType == typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult); -#endif } /// diff --git a/src/bunit.web/JSInterop/JSRuntimeUnhandledInvocationException.cs b/src/bunit.web/JSInterop/JSRuntimeUnhandledInvocationException.cs index 875d3a852..95fcc126f 100644 --- a/src/bunit.web/JSInterop/JSRuntimeUnhandledInvocationException.cs +++ b/src/bunit.web/JSInterop/JSRuntimeUnhandledInvocationException.cs @@ -118,18 +118,12 @@ private static string GetGenericInvocationArguments(JSRuntimeInvocation invocati } } -#if NET5_0_OR_GREATER private static bool IsImportModuleInvocation(JSRuntimeInvocation invocation) { const string DefaultImportIdentifier = "import"; return string.Equals(invocation.Identifier, DefaultImportIdentifier, StringComparison.Ordinal) && typeof(IJSObjectReference).IsAssignableFrom(invocation.ResultType); } -#else - [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Method to allow compatibility with netstandard2.1")] - private static bool IsImportModuleInvocation(JSRuntimeInvocation runtimeInvocation) - => false; -#endif private static string GetArguments(JSRuntimeInvocation invocation, bool includeIdentifier = true) { diff --git a/src/bunit.web/Rendering/BunitHtmlParser.cs b/src/bunit.web/Rendering/BunitHtmlParser.cs index f56c008b4..0551f71c8 100644 --- a/src/bunit.web/Rendering/BunitHtmlParser.cs +++ b/src/bunit.web/Rendering/BunitHtmlParser.cs @@ -20,7 +20,7 @@ public sealed class BunitHtmlParser : IDisposable private static readonly string[] SpecialHtmlElements = { "HTML", "HEAD", "BODY", "!DOCTYPE" }; private readonly IBrowsingContext context; - private readonly IHtmlParser htmlParser; + private readonly HtmlParser htmlParser; private readonly List documents = new(); /// @@ -59,8 +59,7 @@ private BunitHtmlParser(IConfiguration angleSharpConfiguration) /// The . public INodeList Parse([StringSyntax("Html")]string markup) { - if (markup is null) - throw new ArgumentNullException(nameof(markup)); + ArgumentNullException.ThrowIfNull(markup); var document = GetNewDocumentAsync().GetAwaiter().GetResult(); @@ -71,7 +70,7 @@ public INodeList Parse([StringSyntax("Html")]string markup) : htmlParser.ParseFragment(markup, ctx!); } - private INodeList ParseSpecial(string markup, string matchedElement) + private SingleNodeNodeList ParseSpecial(string markup, string matchedElement) { var doc = htmlParser.ParseDocument(markup); diff --git a/src/bunit.web/Rendering/Internal/Htmlizer.cs b/src/bunit.web/Rendering/Internal/Htmlizer.cs index 24c42b7c7..fc7811d98 100644 --- a/src/bunit.web/Rendering/Internal/Htmlizer.cs +++ b/src/bunit.web/Rendering/Internal/Htmlizer.cs @@ -41,10 +41,7 @@ internal static class Htmlizer public static bool IsBlazorAttribute(string attributeName) { - if (attributeName is null) - { - throw new ArgumentNullException(nameof(attributeName)); - } + ArgumentNullException.ThrowIfNull(attributeName); return attributeName.StartsWith(BlazorAttrPrefix, StringComparison.Ordinal) || attributeName.StartsWith(BlazorCssScopeAttrPrefix, StringComparison.Ordinal); diff --git a/src/bunit.web/Rendering/WebTestRenderer.cs b/src/bunit.web/Rendering/WebTestRenderer.cs index 0e710b50a..3a9a87a4b 100644 --- a/src/bunit.web/Rendering/WebTestRenderer.cs +++ b/src/bunit.web/Rendering/WebTestRenderer.cs @@ -1,11 +1,4 @@ -#if NET5_0_OR_GREATER -using Microsoft.AspNetCore.Components; -using Microsoft.Extensions.DependencyInjection; -#endif using Microsoft.Extensions.Logging; -#if NET5_0_OR_GREATER -using Microsoft.JSInterop; -#endif namespace Bunit.Rendering; @@ -21,12 +14,9 @@ public class WebTestRenderer : TestRenderer public WebTestRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory) : base(renderedComponentActivator, services, loggerFactory) { -#if NET5_0_OR_GREATER ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); -#endif } -#if NET5_0_OR_GREATER /// /// Initializes a new instance of the class. /// @@ -35,5 +25,4 @@ public WebTestRenderer(IRenderedComponentActivator renderedComponentActivator, T { ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } -#endif -} \ No newline at end of file +} diff --git a/src/bunit.web/TestContext.cs b/src/bunit.web/TestContext.cs index 315aa4ddf..a0ada8011 100644 --- a/src/bunit.web/TestContext.cs +++ b/src/bunit.web/TestContext.cs @@ -86,14 +86,10 @@ protected override ITestRenderer CreateTestRenderer() { var renderedComponentActivator = Services.GetRequiredService(); var logger = Services.GetRequiredService(); -#if !NET5_0_OR_GREATER - return new WebTestRenderer(renderedComponentActivator, Services, logger); -#else + var componentActivator = Services.GetService(); return componentActivator is null ? new WebTestRenderer(renderedComponentActivator, Services, logger) : new WebTestRenderer(renderedComponentActivator, Services, logger, componentActivator); -#endif - } } diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationExtensions.cs b/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationExtensions.cs index 366c35a11..ed10641c4 100644 --- a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationExtensions.cs +++ b/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationExtensions.cs @@ -16,8 +16,7 @@ public static class FakeAuthorizationExtensions /// public static TestAuthorizationContext AddTestAuthorization(this TestContextBase context) { - if (context is null) - throw new ArgumentNullException(nameof(context)); + ArgumentNullException.ThrowIfNull(context); context.RenderTree.TryAdd(); context.Services.AddSingleton(); diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs b/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs index 474bb000a..928f697c5 100644 --- a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs +++ b/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs @@ -61,8 +61,7 @@ public void SetRoles(IEnumerable roles) /// Result of authorize request. public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) { - if (requirements is null) - throw new ArgumentNullException(nameof(requirements)); + ArgumentNullException.ThrowIfNull(requirements); AuthorizationResult result; diff --git a/src/bunit.web/TestDoubles/Components/CapturedParameterView{TComponent}.cs b/src/bunit.web/TestDoubles/Components/CapturedParameterView{TComponent}.cs index d10be16cc..6129730b3 100644 --- a/src/bunit.web/TestDoubles/Components/CapturedParameterView{TComponent}.cs +++ b/src/bunit.web/TestDoubles/Components/CapturedParameterView{TComponent}.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using System.Collections; using System.Collections.Immutable; using System.Linq.Expressions; @@ -68,8 +67,7 @@ public bool TryGetValue(string key, [MaybeNullWhen(false)] out object value) /// The . public TValue Get(Expression> parameterSelector) { - if (parameterSelector is null) - throw new ArgumentNullException(nameof(parameterSelector)); + ArgumentNullException.ThrowIfNull(parameterSelector); if (parameterSelector.Body is not MemberExpression { Member: PropertyInfo propInfoCandidate }) throw new ArgumentException($"The parameter selector '{parameterSelector}' does not resolve to a public property on the component '{typeof(TComponent)}'.", nameof(parameterSelector)); @@ -108,4 +106,3 @@ IEnumerator IEnumerable.GetEnumerator() public static CapturedParameterView From(ParameterView parameters) => new(parameters.ToDictionary()!); } -#endif diff --git a/src/bunit.web/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs b/src/bunit.web/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs index 9cb924278..4595d2667 100644 --- a/src/bunit.web/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs +++ b/src/bunit.web/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.TestDoubles; /// @@ -41,4 +40,3 @@ protected virtual void BuildRenderTree(RenderTreeBuilder builder) { } [SuppressMessage("Design", "CA1033:Interface methods should be callable by child types", Justification = "This method is called by the Blazor runtime. Should not be called by inheriting types.")] void IComponent.Attach(RenderHandle renderHandle) => this.renderHandle = renderHandle; } -#endif diff --git a/src/bunit.web/TestDoubles/Components/ParameterNotFoundException.cs b/src/bunit.web/TestDoubles/Components/ParameterNotFoundException.cs index cb569b8b9..0782229b3 100644 --- a/src/bunit.web/TestDoubles/Components/ParameterNotFoundException.cs +++ b/src/bunit.web/TestDoubles/Components/ParameterNotFoundException.cs @@ -1,8 +1,7 @@ -#if NET5_0_OR_GREATER namespace Bunit.TestDoubles; /// -/// Represents an exception which is thrown when the +/// Represents an exception which is thrown when the /// /// is used to get a parameter that was not passed to the doubled component. /// @@ -22,4 +21,3 @@ private ParameterNotFoundException(SerializationInfo info, StreamingContext cont { } } -#endif diff --git a/src/bunit.web/TestDoubles/Components/Stub{TComponent}.cs b/src/bunit.web/TestDoubles/Components/Stub{TComponent}.cs index 78625eb33..9a1913218 100644 --- a/src/bunit.web/TestDoubles/Components/Stub{TComponent}.cs +++ b/src/bunit.web/TestDoubles/Components/Stub{TComponent}.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using System.Diagnostics; namespace Bunit.TestDoubles; @@ -51,4 +50,3 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) } } } -#endif diff --git a/src/bunit.web/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs b/src/bunit.web/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs index 8fd109bee..108e64718 100644 --- a/src/bunit.web/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs +++ b/src/bunit.web/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs @@ -1,4 +1,3 @@ -#if NET6_0_OR_GREATER using Microsoft.Extensions.Logging; namespace Bunit.TestDoubles; @@ -31,4 +30,3 @@ public ValueTask LogErrorAsync(Exception exception) return ValueTask.CompletedTask; } } -#endif diff --git a/src/bunit.web/TestDoubles/Localization/MissingMockStringLocalizationException.cs b/src/bunit.web/TestDoubles/Localization/MissingMockStringLocalizationException.cs index 4ce43d8b1..f6182cf52 100644 --- a/src/bunit.web/TestDoubles/Localization/MissingMockStringLocalizationException.cs +++ b/src/bunit.web/TestDoubles/Localization/MissingMockStringLocalizationException.cs @@ -27,19 +27,15 @@ public MissingMockStringLocalizationException(string methodName, params object?[ private MissingMockStringLocalizationException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { - if (serializationInfo is null) - throw new ArgumentNullException(nameof(serializationInfo)); + ArgumentNullException.ThrowIfNull(serializationInfo); Arguments = serializationInfo.GetValue(nameof(Arguments), Array.Empty().GetType()) as object?[] ?? Array.Empty(); } /// ¨ -#if NET8_0_OR_GREATER [Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId = "SYSLIB0051", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] -#endif public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info is null) - throw new ArgumentNullException(nameof(info)); + ArgumentNullException.ThrowIfNull(info); info.AddValue(nameof(Arguments), Arguments, Array.Empty().GetType()); base.GetObjectData(info, context); } diff --git a/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs b/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs index 574807cf3..12c9e7bdb 100644 --- a/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs +++ b/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs @@ -33,42 +33,6 @@ public FakeNavigationManager(TestContextBase testContextBase) Initialize("http://localhost/", "http://localhost/"); } -#if !NET6_0_OR_GREATER - /// - protected override void NavigateToCore(string uri, bool forceLoad) - { - var absoluteUri = GetNewAbsoluteUri(uri); - var changedBaseUri = HasDifferentBaseUri(absoluteUri); - - if (changedBaseUri) - { - BaseUri = GetBaseUri(absoluteUri); - } - - Uri = ToAbsoluteUri(uri).OriginalString; - history.Push(new NavigationHistory(uri, new NavigationOptions(forceLoad))); - - testContextBase.Renderer.Dispatcher.InvokeAsync(() => - { - Uri = absoluteUri.OriginalString; - - // Only notify of changes if user navigates within the same - // base url (domain). Otherwise, the user navigated away - // from the app, and Blazor's NavigationManager would - // not notify of location changes. - if (!changedBaseUri) - { - NotifyLocationChanged(isInterceptedLink: false); - } - else - { - BaseUri = GetBaseUri(absoluteUri); - } - }); - } -#endif - -#if NET6_0_OR_GREATER /// protected override void NavigateToCore(string uri, NavigationOptions options) { @@ -85,16 +49,11 @@ protected override void NavigateToCore(string uri, NavigationOptions options) if (options.ReplaceHistoryEntry && history.Count > 0) history.Pop(); -#if NET7_0_OR_GREATER HistoryEntryState = options.ForceLoad ? null : options.HistoryEntryState; testContextBase.Renderer.Dispatcher.InvokeAsync(async () => -#else - testContextBase.Renderer.Dispatcher.InvokeAsync(() => -#endif { Uri = absoluteUri.OriginalString; -#if NET7_0_OR_GREATER var shouldContinueNavigation = false; try { @@ -112,10 +71,6 @@ protected override void NavigateToCore(string uri, NavigationOptions options) { return; } -#else - history.Push(new NavigationHistory(uri, options)); -#endif - // Only notify of changes if user navigates within the same // base url (domain). Otherwise, the user navigated away @@ -131,16 +86,13 @@ protected override void NavigateToCore(string uri, NavigationOptions options) } }); } -#endif -#if NET7_0_OR_GREATER /// protected override void SetNavigationLockState(bool value) {} /// protected override void HandleLocationChangingHandlerException(Exception ex, LocationChangingContext context) => throw ex; -#endif private URI GetNewAbsoluteUri(string uri) => new URI(uri, UriKind.RelativeOrAbsolute).IsAbsoluteUri diff --git a/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs b/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs index 9422f7a58..513cfddfc 100644 --- a/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs +++ b/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs @@ -1,15 +1,13 @@ -#if NET7_0_OR_GREATER using System.Text.Json; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.WebAssembly.Authentication; -#endif namespace Bunit.TestDoubles; /// /// Represents a navigation to a with a set of specific navigation . /// -public sealed class NavigationHistory : IEquatable +public sealed record NavigationHistory { /// /// Gets the that was navigated to. @@ -20,14 +18,8 @@ public sealed class NavigationHistory : IEquatable /// /// Gets the options that was specified when the was navigated to. /// -#if !NET6_0_OR_GREATER - public Bunit.TestDoubles.NavigationOptions Options { get; } -#endif -#if NET6_0_OR_GREATER public NavigationOptions Options { get; } -#endif -#if NET7_0_OR_GREATER /// /// Gets the associated with this history entry. /// @@ -40,36 +32,7 @@ public sealed class NavigationHistory : IEquatable /// Will not be null when is . /// public Exception? Exception { get; } -#endif -#if !NET6_0_OR_GREATER - /// - /// Initializes a new instance of the class. - /// - /// - /// - [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Using string to align with NavigationManager")] - public NavigationHistory([StringSyntax(StringSyntaxAttribute.Uri)]string uri, Bunit.TestDoubles.NavigationOptions options) - { - Uri = uri; - Options = options; - } -#endif -#if NET6_0 - /// - /// Initializes a new instance of the class. - /// - /// - /// - [SuppressMessage("Design", "CA1054:URI-like parameters should not be strings", Justification = "Using string to align with NavigationManager")] - public NavigationHistory([StringSyntax(StringSyntaxAttribute.Uri)]string uri, NavigationOptions options) - { - Uri = uri; - Options = options; - } -#endif - -#if NET7_0_OR_GREATER /// /// Initializes a new instance of the class. /// @@ -109,32 +72,6 @@ public NavigationHistory( Options.HistoryEntryState, options ?? JsonSerializerOptions.Default); } -#endif - - /// -#if !NET6_0_OR_GREATER - public bool Equals(NavigationHistory? other) - => other is not null && string.Equals(Uri, other.Uri, StringComparison.Ordinal) && Options.Equals(other.Options); -#endif -#if NET6_0 - public bool Equals(NavigationHistory? other) - => other is not null - && string.Equals(Uri, other.Uri, StringComparison.Ordinal) - && Options.ForceLoad == other.Options.ForceLoad - && Options.ReplaceHistoryEntry == other.Options.ReplaceHistoryEntry; -#endif -#if NET7_0_OR_GREATER - public bool Equals(NavigationHistory? other) - => other is not null - && string.Equals(Uri, other.Uri, StringComparison.Ordinal) - && Options.ForceLoad == other.Options.ForceLoad - && Options.ReplaceHistoryEntry == other.Options.ReplaceHistoryEntry - && State == other.State - && Exception == other.Exception; -#endif - - /// - public override bool Equals(object? obj) => obj is NavigationHistory other && Equals(other); /// public override int GetHashCode() => HashCode.Combine(Uri, Options); diff --git a/src/bunit.web/TestDoubles/NavigationManager/NavigationOptions.cs b/src/bunit.web/TestDoubles/NavigationManager/NavigationOptions.cs deleted file mode 100644 index 4a6ddad2e..000000000 --- a/src/bunit.web/TestDoubles/NavigationManager/NavigationOptions.cs +++ /dev/null @@ -1,32 +0,0 @@ -#if !NET6_0_OR_GREATER -namespace Bunit.TestDoubles; - -/// -/// Additional options for navigating to another URI. -/// -public sealed class NavigationOptions : IEquatable -{ - /// - /// If true, bypasses client-side routing and forces the browser to load the new - /// page from the server, whether or not the URI would normally be handled by the - /// client-side router. - /// - public bool ForceLoad { get; } - - /// - /// Initializes a new instance of the class. - /// - public NavigationOptions(bool forceLoad) => ForceLoad = forceLoad; - - /// - public bool Equals(NavigationOptions? other) - => other is not null && ForceLoad == other.ForceLoad; - - /// - public override bool Equals(object? obj) - => obj is NavigationOptions other && Equals(other); - - /// - public override int GetHashCode() => ForceLoad.GetHashCode(); -} -#endif diff --git a/src/bunit.web/TestDoubles/NavigationManager/NavigationState.cs b/src/bunit.web/TestDoubles/NavigationManager/NavigationState.cs index 4f11ecb44..ea5b6976d 100644 --- a/src/bunit.web/TestDoubles/NavigationManager/NavigationState.cs +++ b/src/bunit.web/TestDoubles/NavigationManager/NavigationState.cs @@ -1,4 +1,3 @@ -#if NET7_0_OR_GREATER namespace Bunit.TestDoubles; /// @@ -21,4 +20,3 @@ public enum NavigationState /// Faulted } -#endif diff --git a/src/bunit.web/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs b/src/bunit.web/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs index 0db5ba9f0..40b2e9df9 100644 --- a/src/bunit.web/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs +++ b/src/bunit.web/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs @@ -1,4 +1,3 @@ -#if NET8_0_OR_GREATER using Microsoft.AspNetCore.Components.Routing; namespace Bunit.TestDoubles; @@ -7,4 +6,3 @@ internal sealed class BunitScrollToLocationHash : IScrollToLocationHash { public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask; } -#endif \ No newline at end of file diff --git a/src/bunit.web/bunit.web.csproj b/src/bunit.web/bunit.web.csproj index 86401722d..131657010 100644 --- a/src/bunit.web/bunit.web.csproj +++ b/src/bunit.web/bunit.web.csproj @@ -1,7 +1,7 @@ - netstandard2.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit Bunit.Web - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/bunit/bunit.csproj b/src/bunit/bunit.csproj index 95d9e8ab4..991e3c475 100644 --- a/src/bunit/bunit.csproj +++ b/src/bunit/bunit.csproj @@ -1,6 +1,6 @@ - netstandard2.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 true false false diff --git a/tests/bunit.core.tests/ComponentFactories/ConditionalComponentFactoryTest.cs b/tests/bunit.core.tests/ComponentFactories/ConditionalComponentFactoryTest.cs index 63717bae5..95ecf78e8 100644 --- a/tests/bunit.core.tests/ComponentFactories/ConditionalComponentFactoryTest.cs +++ b/tests/bunit.core.tests/ComponentFactories/ConditionalComponentFactoryTest.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - namespace Bunit.ComponentFactories; public class ConditionalComponentFactoryTest : TestContext @@ -66,4 +64,3 @@ private static IComponent CreateComponent(Type type, Simple1 simple1, NoArgs noA throw new NotImplementedException($"No mock implementation provided for type {type.FullName}"); } } -#endif diff --git a/tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs b/tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs index 592abab61..cba72719f 100644 --- a/tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs +++ b/tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs @@ -1,12 +1,3 @@ -#if NET5_0_OR_GREATER -using System; -using System.Threading.Tasks; -using Bunit.TestAssets.SampleComponents; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Rendering; -using Shouldly; -using Xunit; - namespace Bunit.ComponentFactories; public class GenericComponentFactoryTest : TestContext @@ -38,4 +29,3 @@ protected override void OnAfterRender(bool firstRender) { } protected override Task OnAfterRenderAsync(bool firstRender) => Task.CompletedTask; } } -#endif diff --git a/tests/bunit.core.tests/ComponentFactories/InstanceComponentFactoryTest.cs b/tests/bunit.core.tests/ComponentFactories/InstanceComponentFactoryTest.cs index 7c149a79e..1beee0b90 100644 --- a/tests/bunit.core.tests/ComponentFactories/InstanceComponentFactoryTest.cs +++ b/tests/bunit.core.tests/ComponentFactories/InstanceComponentFactoryTest.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - namespace Bunit.ComponentFactories; public class InstanceComponentFactoryTest : TestContext @@ -46,4 +44,3 @@ public void Test021() .Add(p => p.Second))); } } -#endif diff --git a/tests/bunit.core.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs b/tests/bunit.core.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs index 8ef7e50b3..1f391718c 100644 --- a/tests/bunit.core.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs +++ b/tests/bunit.core.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - namespace Bunit.ComponentFactories; public class TypeBasedComponentFactoryTest : TestContext @@ -40,6 +38,4 @@ public void Test011() checkIfSubstitute.ShouldNotThrow(); } } -} - -#endif +} \ No newline at end of file diff --git a/tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs b/tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs index 52b596924..fcce39230 100644 --- a/tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs +++ b/tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs @@ -696,7 +696,6 @@ public void Test314() action.ShouldNotThrow(); } -#if NET8_0_OR_GREATER [Fact(DisplayName = "Supplying query string should be reflected in component parameter")] public void Test315() { @@ -725,8 +724,6 @@ public void Test316() NavigationManager.NavigateTo(uri); """); } - -#endif #pragma warning disable S1144 // Unused private types or members should be removed private class Params : ComponentBase @@ -805,7 +802,6 @@ private sealed class ValidNamesComponent : ComponentBase } #pragma warning restore S1144 // Unused private types or members should be removed -#if NET8_0_OR_GREATER private sealed class SupplyFromQueryParameterComponent : ComponentBase { [SupplyParameterFromQuery] public string Query { get; set; } @@ -817,5 +813,4 @@ public override Task SetParametersAsync(ParameterView parameters) return base.SetParametersAsync(parameters); } } -#endif } diff --git a/tests/bunit.core.tests/Rendering/BunitComponentActivatorTest.cs b/tests/bunit.core.tests/Rendering/BunitComponentActivatorTest.cs index 4a7eec427..ce54ecf5d 100644 --- a/tests/bunit.core.tests/Rendering/BunitComponentActivatorTest.cs +++ b/tests/bunit.core.tests/Rendering/BunitComponentActivatorTest.cs @@ -1,5 +1,3 @@ -#if NET5_0_OR_GREATER - using Bunit.TestDoubles; namespace Bunit.Rendering; @@ -57,5 +55,3 @@ public IComponent CreateInstance(Type componentType) } } } - -#endif diff --git a/tests/bunit.core.tests/Rendering/TestRendererTest.cs b/tests/bunit.core.tests/Rendering/TestRendererTest.cs index 06ba766c5..d7347b509 100644 --- a/tests/bunit.core.tests/Rendering/TestRendererTest.cs +++ b/tests/bunit.core.tests/Rendering/TestRendererTest.cs @@ -16,7 +16,7 @@ public TestRendererTest(ITestOutputHelper outputHelper) [Fact(DisplayName = "RenderFragment re-throws exception from component")] public void Test004() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); RenderFragment throwingFragment = b => { b.OpenComponent(0); b.CloseComponent(); }; Should.Throw(() => sut.RenderFragment(throwingFragment)) @@ -26,7 +26,7 @@ public void Test004() [Fact(DisplayName = "RenderComponent re-throws exception from component")] public void Test003() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); Should.Throw(() => sut.RenderComponent()) .Message.ShouldBe(ThrowsDuringSetParams.EXCEPTION.Message); @@ -36,7 +36,7 @@ public void Test003() public void Test001() { const string MARKUP = "

hello world

"; - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = (IRenderedFragment)sut.RenderFragment(builder => builder.AddMarkupContent(0, MARKUP)); @@ -47,7 +47,7 @@ public void Test001() [Fact(DisplayName = "Can render component without children and no parameters")] public void Test002() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent(); @@ -60,7 +60,7 @@ public void Test002() public void Test005() { const string VALUE = "FOO BAR"; - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent((nameof(HasParams.Value), VALUE)); @@ -73,7 +73,7 @@ public void Test006() const string PARENT_VALUE = "PARENT"; const string CHILD_VALUE = "CHILD"; - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( (nameof(HasParams.Value), PARENT_VALUE), @@ -86,7 +86,7 @@ public void Test006() [Fact(DisplayName = "Rendered component gets RenderCount updated on re-render")] public async Task Test010() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent(); @@ -102,7 +102,7 @@ public async Task Test011() { // arrange const string EXPECTED = "NOW VALUE"; - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent(); cut.RenderCount.ShouldBe(1); @@ -122,7 +122,7 @@ public void Test020() const string PARENT_VALUE = "PARENT"; const string CHILD_VALUE = "CHILD"; - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( (nameof(HasParams.Value), PARENT_VALUE), @@ -139,7 +139,7 @@ public void Test020() [Fact(DisplayName = "FindComponent throws if parentComponent parameter is null")] public void Test021() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); Should.Throw(() => sut.FindComponent(null!)); } @@ -147,7 +147,7 @@ public void Test021() [Fact(DisplayName = "FindComponent throws if component is not found")] public void Test022() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent(); Should.Throw(() => sut.FindComponent(cut)); @@ -156,7 +156,7 @@ public void Test022() [Fact(DisplayName = "FindComponent returns same rendered component when called multiple times")] public void Test023() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( ChildContent()); @@ -175,7 +175,7 @@ public void Test030() const string PARENT_VALUE = nameof(PARENT_VALUE); const string CHILD_VALUE = nameof(CHILD_VALUE); - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( (nameof(HasParams.Value), GRAND_PARENT_VALUE), @@ -200,7 +200,7 @@ public void Test030() [Fact(DisplayName = "FindComponents throws if parentComponent parameter is null")] public void Test031() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); Should.Throw(() => sut.FindComponents(null!)); } @@ -209,7 +209,7 @@ public void Test031() public void Test032() { // arrange - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( ChildContent( ChildContent())); @@ -225,7 +225,7 @@ public void Test032() [Fact(DisplayName = "Retrieved rendered child component with FindComponent gets updated on re-render")] public async Task Test040() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var parent = sut.RenderComponent( ChildContent()); @@ -244,7 +244,7 @@ public async Task Test040() [Fact(DisplayName = "Retrieved rendered child component with FindComponents gets updated on re-render")] public async Task Test041() { - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var parent = sut.RenderComponent( ChildContent()); @@ -264,7 +264,7 @@ public async Task Test041() public async Task Test050() { // arrange - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( ChildContent()); @@ -282,7 +282,7 @@ public async Task Test050() public async Task Test060() { // arrange - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( ChildContent()); @@ -300,7 +300,7 @@ public async Task Test060() public async Task Test061() { // arrange - var sut = CreateRenderer(); + using var sut = CreateRenderer(); var cut = sut.RenderComponent( ChildContent( @@ -490,7 +490,6 @@ public void Test208() cut.Instance.AfterRenderAsyncCount.ShouldBe(2); } -#if NET8_0_OR_GREATER [Fact(DisplayName = "Can render components that have a RenderMode InteractiveAuto")] public void Test209() { @@ -514,9 +513,8 @@ public void Test211() cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveWebAssembly}"); } -#endif - private ITestRenderer CreateRenderer() => new WebTestRenderer( + private WebTestRenderer CreateRenderer() => new WebTestRenderer( Services.GetRequiredService(), Services, NullLoggerFactory.Instance); diff --git a/tests/bunit.core.tests/Rendering/TestRendererTest.net5.cs b/tests/bunit.core.tests/Rendering/TestRendererTest.net5.cs index d60e3d78e..4e1fdb621 100644 --- a/tests/bunit.core.tests/Rendering/TestRendererTest.net5.cs +++ b/tests/bunit.core.tests/Rendering/TestRendererTest.net5.cs @@ -1,13 +1,4 @@ -#if NET5_0_OR_GREATER -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Bunit.TestAssets.SampleComponents; -using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Logging.Abstractions; -using Xunit; namespace Bunit.Rendering; @@ -31,4 +22,3 @@ public void Test1000() activatorMock.Received(1).CreateInstance(typeof(Wrapper)); } } -#endif diff --git a/tests/bunit.core.tests/TestContextBaseTest.net5.cs b/tests/bunit.core.tests/TestContextBaseTest.net5.cs index 8734977d7..09af8e57a 100644 --- a/tests/bunit.core.tests/TestContextBaseTest.net5.cs +++ b/tests/bunit.core.tests/TestContextBaseTest.net5.cs @@ -1,6 +1,3 @@ -#if NET5_0_OR_GREATER - -using Bunit.Rendering; using Bunit.TestAssets.SampleComponents.DisposeComponents; namespace Bunit; @@ -174,4 +171,3 @@ private static IComponentFactory CreateMockComponentFactory(Func can return result; } } -#endif diff --git a/tests/bunit.core.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs b/tests/bunit.core.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs index cb3d256a2..dc45b2c52 100644 --- a/tests/bunit.core.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs +++ b/tests/bunit.core.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs @@ -1,12 +1,3 @@ -#if NET6_0_OR_GREATER -using System.Threading.Tasks; -using AutoFixture.Xunit2; -using Bunit.TestAssets.SampleComponents; -using Microsoft.AspNetCore.Components; -using Shouldly; -using Xunit; -using Xunit.Abstractions; - namespace Bunit.TestDoubles; public class FakePersistentComponentStateTest : TestContext @@ -87,4 +78,3 @@ public void Test014() onPersistingCalledTimes.ShouldBe(1); } } -#endif diff --git a/tests/bunit.core.tests/TestServiceProviderTest.cs b/tests/bunit.core.tests/TestServiceProviderTest.cs index bb30995b0..83e6898ae 100644 --- a/tests/bunit.core.tests/TestServiceProviderTest.cs +++ b/tests/bunit.core.tests/TestServiceProviderTest.cs @@ -297,7 +297,6 @@ public void Test039() dummyServiceProvider.ResolvedTestServices.Count.ShouldBe(1); } -#if NET8_0_OR_GREATER [Fact(DisplayName = "Should resolve keyed service from container")] public void Test040() { @@ -329,7 +328,6 @@ public void Test042() Should.Throw(() => ctx.RenderComponent()); } -#endif private sealed class DummyService { } @@ -416,11 +414,9 @@ public IServiceProvider CreateServiceProvider(DummyServiceProviderFactoryContain => containerBuilder.Build(); } -#if NET8_0_OR_GREATER private sealed class ComponentWithKeyedService : ComponentBase { [Inject(Key = "Key")] public DummyService Service { get; set; } } -#endif } diff --git a/tests/bunit.core.tests/bunit.core.tests.csproj b/tests/bunit.core.tests/bunit.core.tests.csproj index 62e64bfdd..fcdc324e8 100644 --- a/tests/bunit.core.tests/bunit.core.tests.csproj +++ b/tests/bunit.core.tests/bunit.core.tests.csproj @@ -1,7 +1,7 @@ - netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit Bunit.Core.Tests diff --git a/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs b/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs index 63d4365b7..48adfd2c5 100644 --- a/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs +++ b/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs @@ -4,15 +4,6 @@ public static class TaskAssertionExtensions { public static async Task ShouldCompleteWithin(this Task task, TimeSpan timeout) { -#if NET6_0_OR_GREATER await task.WaitAsync(timeout); -#else - using var cts = new CancellationTokenSource(); - var delayTask = Task.Delay(timeout, cts.Token); - if (task != await Task.WhenAny(task, delayTask)) - throw new TimeoutException(); - - cts.Cancel(); -#endif } } diff --git a/tests/bunit.testassets/RenderModes/InteractiveAutoComponent.razor b/tests/bunit.testassets/RenderModes/InteractiveAutoComponent.razor index 7b1ed59c1..cfdea5063 100644 --- a/tests/bunit.testassets/RenderModes/InteractiveAutoComponent.razor +++ b/tests/bunit.testassets/RenderModes/InteractiveAutoComponent.razor @@ -1,8 +1,2 @@ -@{ - #if NET8_0_OR_GREATER -} -@rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveAuto -

Hello world @Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveAuto

-@{ - #endif -} +@rendermode RenderMode.InteractiveAuto +

Hello world @RenderMode.InteractiveAuto

diff --git a/tests/bunit.testassets/RenderModes/InteractiveServerComponent.razor b/tests/bunit.testassets/RenderModes/InteractiveServerComponent.razor index 083ef67e3..2df23b227 100644 --- a/tests/bunit.testassets/RenderModes/InteractiveServerComponent.razor +++ b/tests/bunit.testassets/RenderModes/InteractiveServerComponent.razor @@ -1,8 +1,2 @@ -@{ - #if NET8_0_OR_GREATER -} -@rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveServer -

Hello world @Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveServer

-@{ - #endif -} +@rendermode RenderMode.InteractiveServer +

Hello world @RenderMode.InteractiveServer

diff --git a/tests/bunit.testassets/RenderModes/InteractiveWebAssemblyComponent.razor b/tests/bunit.testassets/RenderModes/InteractiveWebAssemblyComponent.razor index 0ed92bfed..cb7c10e58 100644 --- a/tests/bunit.testassets/RenderModes/InteractiveWebAssemblyComponent.razor +++ b/tests/bunit.testassets/RenderModes/InteractiveWebAssemblyComponent.razor @@ -1,8 +1,2 @@ -@{ - #if NET8_0_OR_GREATER -} -@rendermode Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveWebAssembly -

Hello world @Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveWebAssembly

-@{ - #endif -} +@rendermode RenderMode.InteractiveWebAssembly +

Hello world @RenderMode.InteractiveWebAssembly

diff --git a/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs b/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs index 6f4532ff7..1171bd768 100644 --- a/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs +++ b/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs @@ -6,7 +6,6 @@ public partial class PersistentComponentStateSample public WeatherForecast[] Forecasts { get; private set; } -#if NET6_0_OR_GREATER [Inject] public PersistentComponentState State { get; set; } protected override void OnInitialized() @@ -35,7 +34,6 @@ private WeatherForecast[] CreateForecasts() new WeatherForecast{ Temperature = 42 }, }; } -#endif } public record class WeatherForecast diff --git a/tests/bunit.testassets/SampleComponents/TriggerTester.cs b/tests/bunit.testassets/SampleComponents/TriggerTester.cs index e07787a4d..a6316b326 100644 --- a/tests/bunit.testassets/SampleComponents/TriggerTester.cs +++ b/tests/bunit.testassets/SampleComponents/TriggerTester.cs @@ -9,8 +9,7 @@ public class TriggerTester : ComponentBase protected override void BuildRenderTree(RenderTreeBuilder builder) { - if (builder is null) - throw new ArgumentNullException(nameof(builder)); + ArgumentNullException.ThrowIfNull(builder); if (TriggeredEvent is null) throw new InvalidOperationException($"{nameof(TriggeredEvent)} is null"); diff --git a/tests/bunit.testassets/Serilog.Sinks.XUnit/TestOutputSink.cs b/tests/bunit.testassets/Serilog.Sinks.XUnit/TestOutputSink.cs index e18364d0c..16b449e8d 100644 --- a/tests/bunit.testassets/Serilog.Sinks.XUnit/TestOutputSink.cs +++ b/tests/bunit.testassets/Serilog.Sinks.XUnit/TestOutputSink.cs @@ -26,8 +26,7 @@ public TestOutputSink(ITestOutputHelper testOutputHelper, ITextFormatter textFor public void Emit(LogEvent logEvent) { - if (logEvent == null) - throw new ArgumentNullException(nameof(logEvent)); + ArgumentNullException.ThrowIfNull(logEvent); using var renderSpace = new StringWriter(); textFormatter.Format(logEvent, renderSpace); diff --git a/tests/bunit.testassets/Serilog.Sinks.XUnit/XUnitLoggerConfigurationExtensions.cs b/tests/bunit.testassets/Serilog.Sinks.XUnit/XUnitLoggerConfigurationExtensions.cs index 6b34f17db..a5f831cd5 100644 --- a/tests/bunit.testassets/Serilog.Sinks.XUnit/XUnitLoggerConfigurationExtensions.cs +++ b/tests/bunit.testassets/Serilog.Sinks.XUnit/XUnitLoggerConfigurationExtensions.cs @@ -35,10 +35,8 @@ public static LoggerConfiguration TestOutput( IFormatProvider formatProvider = null, LoggingLevelSwitch levelSwitch = null) { - if (sinkConfiguration == null) - throw new ArgumentNullException(nameof(sinkConfiguration)); - if (messageSink == null) - throw new ArgumentNullException(nameof(messageSink)); + ArgumentNullException.ThrowIfNull(sinkConfiguration); + ArgumentNullException.ThrowIfNull(messageSink); var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); @@ -64,10 +62,8 @@ public static LoggerConfiguration TestOutput( LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, LoggingLevelSwitch levelSwitch = null) { - if (sinkConfiguration == null) - throw new ArgumentNullException(nameof(sinkConfiguration)); - if (formatter == null) - throw new ArgumentNullException(nameof(formatter)); + ArgumentNullException.ThrowIfNull(sinkConfiguration); + ArgumentNullException.ThrowIfNull(formatter); return sinkConfiguration.Sink(new TestOutputSink(messageSink, formatter), restrictedToMinimumLevel, levelSwitch); } @@ -92,10 +88,8 @@ public static LoggerConfiguration TestOutput( IFormatProvider formatProvider = null, LoggingLevelSwitch levelSwitch = null) { - if (sinkConfiguration == null) - throw new ArgumentNullException(nameof(sinkConfiguration)); - if (testOutputHelper == null) - throw new ArgumentNullException(nameof(testOutputHelper)); + ArgumentNullException.ThrowIfNull(sinkConfiguration); + ArgumentNullException.ThrowIfNull(testOutputHelper); var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider); @@ -121,10 +115,8 @@ public static LoggerConfiguration TestOutput( LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, LoggingLevelSwitch levelSwitch = null) { - if (sinkConfiguration == null) - throw new ArgumentNullException(nameof(sinkConfiguration)); - if (formatter == null) - throw new ArgumentNullException(nameof(formatter)); + ArgumentNullException.ThrowIfNull(sinkConfiguration); + ArgumentNullException.ThrowIfNull(formatter); return sinkConfiguration.Sink(new TestOutputSink(testOutputHelper, formatter), restrictedToMinimumLevel, levelSwitch); } diff --git a/tests/bunit.testassets/bunit.testassets.csproj b/tests/bunit.testassets/bunit.testassets.csproj index d9746eafc..34ab4c79b 100644 --- a/tests/bunit.testassets/bunit.testassets.csproj +++ b/tests/bunit.testassets/bunit.testassets.csproj @@ -1,7 +1,7 @@ - netstandard2.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit.TestAssets Bunit.TestAssets Library @@ -20,32 +20,7 @@
- - - - - - - - - - - - - - - - - - - - - - - - - - + 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 f37f4ff1d..b3b2dfa52 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 @@ - netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit Bunit.Web.Query.Tests diff --git a/tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs b/tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs index 4e241932e..d455b112d 100644 --- a/tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs +++ b/tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs @@ -1,8 +1,3 @@ -#if !NETCOREAPP3_1 - -using Bunit.TestAssets.SampleComponents; -using Xunit; - namespace Bunit.Asserting; public partial class MarkupMatchesAssertExtensionsTest : TestContext @@ -15,4 +10,3 @@ public void Test_net5_001() cut.MarkupMatches("

Hello Pink World!

"); } } -#endif diff --git a/tests/bunit.web.tests/ComponentFactories/StubComponentFactoryTest.cs b/tests/bunit.web.tests/ComponentFactories/StubComponentFactoryTest.cs index 5bd566ce0..72801de80 100644 --- a/tests/bunit.web.tests/ComponentFactories/StubComponentFactoryTest.cs +++ b/tests/bunit.web.tests/ComponentFactories/StubComponentFactoryTest.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER using Bunit.TestDoubles; namespace Bunit.ComponentFactories; @@ -115,6 +114,4 @@ public void Test024(string randomText) private class CompA : ComponentBase { } private sealed class CompDerivedA : CompA { } -} - -#endif +} \ No newline at end of file diff --git a/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs b/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs index 9eaeb5c50..eb1ad67d7 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs @@ -1,5 +1,3 @@ -#if !NETCOREAPP3_1 - namespace Bunit.EventDispatchExtensions; public class DetailsElementEventDispatcherExtensionsTest : TestContext @@ -15,4 +13,3 @@ public void Test200() cut.FindAll("div > p").Count.ShouldBe(1); } } -#endif diff --git a/tests/bunit.web.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs b/tests/bunit.web.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs index bc00d99df..005fa7037 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs @@ -23,8 +23,7 @@ protected TriggerEventSpy CreateTriggerSpy(string element, string eve protected void VerifyEventRaisesCorrectly(MethodInfo helper, TEventArgs expected, params (string MethodName, string EventName)[] methodNameEventMap) { - if (helper is null) - throw new ArgumentNullException(nameof(helper)); + ArgumentNullException.ThrowIfNull(helper); var eventName = methodNameEventMap.SingleOrDefault(x => x.MethodName.Equals(helper.Name, StringComparison.Ordinal)).EventName ?? GetEventNameFromMethod(helper); @@ -71,8 +70,7 @@ protected void VerifyEventRaisesCorrectly(MethodInfo helper, TEventArgs expected [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "Event names are used in lower case.")] private static string GetEventNameFromMethod(MethodInfo helper) { - if (helper is null) - throw new ArgumentNullException(nameof(helper)); + ArgumentNullException.ThrowIfNull(helper); var nameLength = helper.Name.Length; @@ -89,8 +87,7 @@ private static string GetEventNameFromMethod(MethodInfo helper) [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "Can safely be shared")] public static IEnumerable GetEventHelperMethods(Type helperClassType) { - if (helperClassType is null) - throw new ArgumentNullException(nameof(helperClassType)); + ArgumentNullException.ThrowIfNull(helperClassType); return helperClassType.GetMethods() .Where(x => x.GetParameters().FirstOrDefault()?.ParameterType == typeof(IElement)) @@ -101,8 +98,7 @@ public static IEnumerable GetEventHelperMethods(Type helperClassType) [SuppressMessage("Design", "CA1000:Do not declare static members on generic types", Justification = "Can safely be shared")] public static IEnumerable GetEventHelperMethods(Type helperClassType, Func customFilter) { - if (helperClassType is null) - throw new ArgumentNullException(nameof(helperClassType)); + ArgumentNullException.ThrowIfNull(helperClassType); return helperClassType.GetMethods() .Where(x => x.GetParameters().FirstOrDefault()?.ParameterType == typeof(IElement) && customFilter(x)) diff --git a/tests/bunit.web.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs b/tests/bunit.web.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs index 6d693c7aa..b7461f78d 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs @@ -18,10 +18,7 @@ public GeneralEventDispatchExtensionsTest(ITestOutputHelper outputHelper) [MemberData(nameof(GetEventHelperMethods), typeof(GeneralEventDispatchExtensions))] public void CanRaiseEvents(MethodInfo helper) { - if (helper is null) - { - throw new ArgumentNullException(nameof(helper)); - } + ArgumentNullException.ThrowIfNull(helper); if (helper.Name == nameof(TriggerEventDispatchExtensions.TriggerEventAsync)) { @@ -180,7 +177,6 @@ public async Task Test114( cut.Instance.GrandParentTriggerCount.ShouldBe(1); } -#if NET6_0_OR_GREATER [Fact(DisplayName = "TriggerEvent can trigger custom events")] public void Test201() { @@ -194,7 +190,6 @@ public void Test201() cut.Find("p:last-child").MarkupMatches("

You pasted: FOO

"); } -#endif [Fact(DisplayName = "TriggerEventAsync throws NoEventHandlerException when invoked with an unknown event handler ID")] public void Test300() diff --git a/tests/bunit.web.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs b/tests/bunit.web.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs index f96c9107c..83aea6d77 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs @@ -119,7 +119,6 @@ public void Test017(DateTime? value) VerifySingleBindValue(default(DateTime)); } -#if NET6_0_OR_GREATER [Theory(DisplayName = "Change and Input events are raised correctly"), AutoData] [UseCulture("en-US")] public void Test018(DateTimeOffset value) => VerifySingleBindValue(DateTimeWithoutMillisecond(value)); @@ -131,7 +130,6 @@ public void Test019(DateTimeOffset? value) VerifySingleBindValue(DateTimeWithoutMillisecond(value)); VerifySingleBindValue(default(DateTimeOffset)); } -#endif [Theory(DisplayName = "Change and Input events are raised correctly"), AutoData] public void Test020(Foo value) => VerifySingleBindValue(value); @@ -140,14 +138,10 @@ public void Test019(DateTimeOffset? value) public void Test021(Foo? value) => VerifySingleBindValue(value); -#if NET6_0_OR_GREATER - [Fact(DisplayName = "Change and Input events are raised correctly for null object")] public void Test022() => VerifySingleBindValue(default(Foo)); -#endif - [Theory(DisplayName = "Change and Input events are raised correctly"), AutoData] public void Test023(Cars value) => VerifySingleBindValue(value); @@ -158,8 +152,6 @@ public void Test024(Cars? value) VerifySingleBindValue(default(Cars)); } -#if NET6_0_OR_GREATER - [Theory(DisplayName = "Change and Input events are raised correctly"), AutoData] public void Test100(string[] values) => VerifyMultipleBindValue(values); @@ -287,7 +279,6 @@ private void VerifyMultipleBindValue(T[] values) cut.Instance.OnChangeValue.ShouldBe(FormatValues(values)); cut.Instance.OnInputValue.ShouldBe(FormatValues(values)); } -#endif private void VerifySingleBindValue(T value) { diff --git a/tests/bunit.web.tests/EventDispatchExtensions/TriggerEventSpy.cs b/tests/bunit.web.tests/EventDispatchExtensions/TriggerEventSpy.cs index 7a6c949cd..b8b83b0c5 100644 --- a/tests/bunit.web.tests/EventDispatchExtensions/TriggerEventSpy.cs +++ b/tests/bunit.web.tests/EventDispatchExtensions/TriggerEventSpy.cs @@ -13,8 +13,7 @@ public class TriggerEventSpy public TriggerEventSpy(Func>> componentRenderer, string element, string eventName) { - if (componentRenderer is null) - throw new ArgumentNullException(nameof(componentRenderer)); + ArgumentNullException.ThrowIfNull(componentRenderer); renderedComponent = componentRenderer(new ComponentParameter[] { @@ -27,16 +26,14 @@ public TriggerEventSpy(Func trigger) { - if (trigger is null) - throw new ArgumentNullException(nameof(trigger)); + ArgumentNullException.ThrowIfNull(trigger); trigger(renderedComponent.Find(element)); } public Task Trigger(Func trigger) { - if (trigger is null) - throw new ArgumentNullException(nameof(trigger)); + ArgumentNullException.ThrowIfNull(trigger); return trigger(renderedComponent.Find(element)); } diff --git a/tests/bunit.web.tests/Extensions/InputFile/InputFileTests.cs b/tests/bunit.web.tests/Extensions/InputFile/InputFileTests.cs index e0e63ad83..44b418f7c 100644 --- a/tests/bunit.web.tests/Extensions/InputFile/InputFileTests.cs +++ b/tests/bunit.web.tests/Extensions/InputFile/InputFileTests.cs @@ -1,5 +1,4 @@ -#if NET5_0_OR_GREATER -using System.Text; +using System.Text; using Microsoft.AspNetCore.Components.CompilerServices; using Microsoft.AspNetCore.Components.Forms; @@ -175,4 +174,3 @@ private void OnChange(InputFileChangeEventArgs args) public sealed record File(string Filename, string FileContent, DateTimeOffset LastChanged, long Size, string Type); } } -#endif diff --git a/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.net5.cs b/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.net5.cs index 5f32096d6..3262c6723 100644 --- a/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.net5.cs +++ b/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.net5.cs @@ -1,12 +1,5 @@ -#if !NETCOREAPP3_1 && !NET9_0_OR_GREATER +#if !NET9_0_OR_GREATER #pragma warning disable CS0618 // This method is obsolete. -using System; -using System.Linq; -using AutoFixture.Xunit2; -using Microsoft.JSInterop; -using Shouldly; -using Xunit; - namespace Bunit.JSInterop; public partial class BunitJSInteropTest diff --git a/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs b/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs index 89ca70086..2e2e29e1f 100644 --- a/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs +++ b/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs @@ -1,4 +1,3 @@ -#if !NETCOREAPP3_1 using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -15,11 +14,7 @@ namespace Bunit.JSInterop; public class BunitJSObjectReferenceTest : TestContext { private static readonly Type JSVoidResultType = -#if !NET6_0_OR_GREATER - typeof(object); -#else typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult); -#endif [Theory(DisplayName = "Calling Setup or Setup throws")] [InlineData("import", null)] @@ -275,7 +270,7 @@ public void Test071() public async Task Test080() { JSInterop.Mode = JSRuntimeMode.Loose; - var jsInProcess = (IJSInProcessObjectReference)GetBunitJSObjectReference(); + var jsInProcess = GetBunitJSObjectReference(); await jsInProcess.InvokeAsync("bar1"); await jsInProcess.InvokeAsync("bar2", "baz"); @@ -285,11 +280,11 @@ public async Task Test080() jsInProcess.Invoke("bar6", "baz"); JSInterop.VerifyInvoke("bar1"); - JSInterop.VerifyInvoke("bar2").Arguments.ShouldBe(new[] { "baz" }); + JSInterop.VerifyInvoke("bar2").Arguments.ShouldBe(["baz"]); JSInterop.VerifyInvoke("bar3"); - JSInterop.VerifyInvoke("bar4").Arguments.ShouldBe(new[] { "baz" }); + JSInterop.VerifyInvoke("bar4").Arguments.ShouldBe(["baz"]); JSInterop.VerifyInvoke("bar5"); - JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(new[] { "baz" }); + JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(["baz"]); } #if !NET9_0_OR_GREATER @@ -311,15 +306,15 @@ public async Task Test081() jsUnmarshalled.InvokeUnmarshalled("bar10", "baz", "boo", "bah"); JSInterop.VerifyInvoke("bar1"); - JSInterop.VerifyInvoke("bar2").Arguments.ShouldBe(new[] { "baz" }); + JSInterop.VerifyInvoke("bar2").Arguments.ShouldBe(["baz"]); JSInterop.VerifyInvoke("bar3"); - JSInterop.VerifyInvoke("bar4").Arguments.ShouldBe(new[] { "baz" }); + JSInterop.VerifyInvoke("bar4").Arguments.ShouldBe(["baz"]); JSInterop.VerifyInvoke("bar5"); - JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(new[] { "baz" }); + JSInterop.VerifyInvoke("bar6").Arguments.ShouldBe(["baz"]); JSInterop.VerifyInvoke("bar7"); - JSInterop.VerifyInvoke("bar8").Arguments.ShouldBe(new[] { "baz" }); - JSInterop.VerifyInvoke("bar9").Arguments.ShouldBe(new[] { "baz", "boo" }); - JSInterop.VerifyInvoke("bar10").Arguments.ShouldBe(new[] { "baz", "boo", "bah" }); + 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] @@ -471,4 +466,3 @@ public void Test305(string identifier, string[] args) private BunitJSObjectReference GetBunitJSObjectReference() => (BunitJSObjectReference)JSInterop.JSRuntime.InvokeAsync("FOO.js").Result; } -#endif diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs b/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs index 66b3aab95..709a78ff5 100644 --- a/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs +++ b/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs @@ -1,10 +1,3 @@ -#if !NETCOREAPP3_1 -using System.Threading.Tasks; -using Bunit.TestAssets.SampleComponents; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Rendering; -using Xunit; - namespace Bunit.JSInterop.InvocationHandlers; public class FocusAsyncInvocationHandlerTest : TestContext @@ -59,4 +52,3 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) } } } -#endif diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs b/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs index b6c3bc72f..f641b2601 100644 --- a/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs +++ b/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs @@ -1,15 +1,3 @@ -#if NET6_0_OR_GREATER -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Bunit.TestAssets.SampleComponents; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Routing; -using Shouldly; -using Xunit; - namespace Bunit.JSInterop.InvocationHandlers; public class FocusOnNavigateHandlerTest : TestContext @@ -56,4 +44,3 @@ protected override async Task OnAfterRenderAsync(bool firstRender) } } } -#endif diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs b/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs index 7df771ecb..a097d16f5 100644 --- a/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs +++ b/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs @@ -1,11 +1,4 @@ -#if !NETCOREAPP3_1 -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Web.Virtualization; -using Shouldly; -using Xunit; namespace Bunit.JSInterop.ComponentSupport; @@ -97,7 +90,7 @@ public void Test040(int itemsInDataSource) cut.FindAll(".item").Count.ShouldBe(0); } - private static ICollection CreateItems(int itemsToCreate) + private static string[] CreateItems(int itemsToCreate) => Enumerable.Range(0, itemsToCreate).Select(_ => Guid.NewGuid().ToString()).ToArray(); private static ItemsProviderDelegate CreateItemsProvider(int itemsInCollection) @@ -111,5 +104,3 @@ private static ItemsProviderDelegate CreateItemsProvider(int itemsInColl }; } } - -#endif diff --git a/tests/bunit.web.tests/JSInterop/JSRuntimeInvocationTest.cs b/tests/bunit.web.tests/JSInterop/JSRuntimeInvocationTest.cs index fa14e3867..dfc670b71 100644 --- a/tests/bunit.web.tests/JSInterop/JSRuntimeInvocationTest.cs +++ b/tests/bunit.web.tests/JSInterop/JSRuntimeInvocationTest.cs @@ -3,12 +3,8 @@ namespace Bunit.JSInterop; public class JSRuntimeInvocationTest { private static readonly Type JSVoidResultType = -#if !NET6_0_OR_GREATER - typeof(object); -#else typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult); -#endif - + public static IEnumerable GetEqualsTestData() { var token = new CancellationToken(true); diff --git a/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs b/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs index 00ec62014..4290db952 100644 --- a/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs +++ b/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs @@ -7,11 +7,7 @@ public partial class JSRuntimeUnhandledInvocationExceptionTest private const string CodeIdent = " "; private static readonly Type JSVoidResultType = -#if !NET6_0_OR_GREATER - typeof(object); -#else typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult); -#endif private static string CreateExpectedErrorMessage(string invocationMethod, string suggestedSetup) { diff --git a/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs b/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs index cfc1e55d6..a281ba6ea 100644 --- a/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs +++ b/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs @@ -1,10 +1,3 @@ -#if NET5_0_OR_GREATER -using System; -using System.Diagnostics.CodeAnalysis; -using AutoFixture.Xunit2; -using Microsoft.JSInterop; -using Xunit; - namespace Bunit.JSInterop; public partial class JSRuntimeUnhandledInvocationExceptionTest @@ -25,4 +18,3 @@ public void Test036(string moduleName) Assert.Equal(expectedErrorMessage, sut.Message); } } -#endif diff --git a/tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs b/tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs index 03f6f5588..a2ef4e592 100644 --- a/tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs +++ b/tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs @@ -1,7 +1,3 @@ -#if !NETCOREAPP3_1 -using Shouldly; -using Xunit; - namespace Bunit.Rendering.Internal; public partial class HtmlizerTests : TestContext @@ -16,4 +12,3 @@ public void TestNET5_001(string blazorAttribute) Htmlizer.IsBlazorAttribute(blazorAttribute).ShouldBeTrue(); } } -#endif diff --git a/tests/bunit.web.tests/TestContextTest.net6.cs b/tests/bunit.web.tests/TestContextTest.net6.cs index 9437b657a..9ba770e7c 100644 --- a/tests/bunit.web.tests/TestContextTest.net6.cs +++ b/tests/bunit.web.tests/TestContextTest.net6.cs @@ -1,10 +1,3 @@ -#if NET6_0_OR_GREATER -using AutoFixture.Xunit2; -using Bunit.TestAssets.SampleComponents; -using Microsoft.AspNetCore.Components.Web; -using Shouldly; -using Xunit; - namespace Bunit; public partial class TestContextTest : TestContext @@ -16,4 +9,3 @@ public void Test001() logger.ShouldNotBe(null); } } -#endif diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs b/tests/bunit.web.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs index e69243da0..74da5968e 100644 --- a/tests/bunit.web.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs +++ b/tests/bunit.web.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs @@ -68,7 +68,7 @@ public void Test001() // assert Assert.True(authContext.IsAuthenticated); Assert.Equal(AuthorizationState.Authorized, authContext.State); - Assert.Equal(new[] { "some-role" }, authContext.Roles); + Assert.Equal(["some-role"], authContext.Roles); Assert.Empty(authContext.Policies); } @@ -83,7 +83,7 @@ public void Test0011() // assert Assert.True(authContext.IsAuthenticated); Assert.Equal(AuthorizationState.Authorized, authContext.State); - Assert.Equal(new[] { "TestPolicy", "Other" }, authContext.Policies); + Assert.Equal(["TestPolicy", "Other"], authContext.Policies); Assert.Empty(authContext.Roles); } } diff --git a/tests/bunit.web.tests/TestDoubles/Components/CapturedParameterViewTest.cs b/tests/bunit.web.tests/TestDoubles/Components/CapturedParameterViewTest.cs index 1cd82ba60..4792fb076 100644 --- a/tests/bunit.web.tests/TestDoubles/Components/CapturedParameterViewTest.cs +++ b/tests/bunit.web.tests/TestDoubles/Components/CapturedParameterViewTest.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.TestDoubles.Components; public class CapturedParameterViewTest @@ -66,4 +65,3 @@ public void Test021() sut.Get(x => x.UnnamedCascadingValue).ShouldBeNull(); } } -#endif diff --git a/tests/bunit.web.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs b/tests/bunit.web.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs index aeb80015b..3cc30aafb 100644 --- a/tests/bunit.web.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs +++ b/tests/bunit.web.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.TestDoubles.Components; public class ComponentDoubleBaseTest : TestContext @@ -16,4 +15,3 @@ public void Test022(string attrName, string attrValue) cut.Instance.Parameters[attrName].ShouldBe(attrValue); } } -#endif diff --git a/tests/bunit.web.tests/TestDoubles/Components/StubTest.cs b/tests/bunit.web.tests/TestDoubles/Components/StubTest.cs index f6492e588..0cc4acbec 100644 --- a/tests/bunit.web.tests/TestDoubles/Components/StubTest.cs +++ b/tests/bunit.web.tests/TestDoubles/Components/StubTest.cs @@ -1,4 +1,3 @@ -#if NET5_0_OR_GREATER namespace Bunit.TestDoubles.Components; public class StubTest : TestContext @@ -27,4 +26,3 @@ public void Test002(string header, string attrValue) ps => ps.Count.ShouldBe(2)); } } -#endif diff --git a/tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs b/tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs index e8a274fab..2c74eef40 100644 --- a/tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs +++ b/tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs @@ -104,22 +104,7 @@ public void Test007() sut.Uri.ShouldEndWith("with%20whitespace"); } - -#if !NET6_0_OR_GREATER - [Theory(DisplayName = "NavigateTo(uri, forceLoad) is saved in history")] - [InlineData("/uri", false)] - [InlineData("/anotherUri", true)] - public void Test100(string uri, bool forceLoad) - { - var sut = CreateFakeNavigationManager(); - - sut.NavigateTo(uri, forceLoad); - - sut.History.ShouldHaveSingleItem() - .ShouldBeEquivalentTo(new NavigationHistory(uri, new NavigationOptions(forceLoad))); - } -#endif -#if NET6_0_OR_GREATER + [Theory(DisplayName = "NavigateTo(uri, forceLoad, replaceHistoryEntry) is saved in history")] [InlineData("/uri", false, false)] [InlineData("/uri", true, false)] @@ -129,17 +114,11 @@ public void Test200(string uri, bool forceLoad, bool replaceHistoryEntry) var sut = CreateFakeNavigationManager(); sut.NavigateTo(uri, forceLoad, replaceHistoryEntry); - -#if NET6_0 - sut.History.ShouldHaveSingleItem() - .ShouldBeEquivalentTo(new NavigationHistory(uri, - new NavigationOptions { ForceLoad = forceLoad, ReplaceHistoryEntry = replaceHistoryEntry })); -#elif NET7_0_OR_GREATER + var navigationOptions = new NavigationOptions { ForceLoad = forceLoad, ReplaceHistoryEntry = replaceHistoryEntry }; sut.History.ShouldHaveSingleItem() .ShouldBeEquivalentTo(new NavigationHistory(uri, navigationOptions, NavigationState.Succeeded)); -#endif } [Fact(DisplayName = "NavigateTo with replaceHistoryEntry true replaces previous history entry")] @@ -150,17 +129,13 @@ public void Test201() sut.NavigateTo("/firstUrl"); sut.NavigateTo("/secondUrl", new NavigationOptions { ReplaceHistoryEntry = true }); -#if NET6_0 - sut.History.ShouldHaveSingleItem() - .ShouldBeEquivalentTo(new NavigationHistory("/secondUrl", - new NavigationOptions { ReplaceHistoryEntry = true })); -#elif NET7_0_OR_GREATER sut.History.ShouldHaveSingleItem() - .ShouldBeEquivalentTo(new NavigationHistory("/secondUrl", new NavigationOptions { ReplaceHistoryEntry = - true }, NavigationState.Succeeded)); -#endif + .ShouldBeEquivalentTo(new NavigationHistory("/secondUrl", new NavigationOptions + { + ReplaceHistoryEntry = + true + }, NavigationState.Succeeded)); } -#endif [Fact(DisplayName = "Navigate to an external url should set BaseUri")] public void Test008() @@ -187,7 +162,6 @@ public void Test009() locationChangedInvoked.ShouldBeFalse(); } -#if NET7_0_OR_GREATER [Fact(DisplayName = "When component provides NavigationLock, FakeNavigationManager should intercept calls")] public void Test010() { @@ -363,6 +337,5 @@ private void InterceptNavigation(LocationChangingContext context) [Inject] private NavigationManager NavigationManager { get; set; } = default!; } -#endif } diff --git a/tests/bunit.web.tests/TestUtilities/MockingHelpers.cs b/tests/bunit.web.tests/TestUtilities/MockingHelpers.cs index b3ff9739b..2ba25ca7a 100644 --- a/tests/bunit.web.tests/TestUtilities/MockingHelpers.cs +++ b/tests/bunit.web.tests/TestUtilities/MockingHelpers.cs @@ -15,8 +15,7 @@ public static class MockingHelpers /// An instance of . public static object ToMockInstance(this Type type) { - if (type is null) - throw new ArgumentNullException(nameof(type)); + ArgumentNullException.ThrowIfNull(type); if (type.IsMockable()) { @@ -37,8 +36,7 @@ public static object ToMockInstance(this Type type) ///
public static bool IsMockable(this Type type) { - if (type is null) - throw new ArgumentNullException(nameof(type)); + ArgumentNullException.ThrowIfNull(type); return !type.IsSealed || type.IsDelegateType(); } diff --git a/tests/bunit.web.tests/bunit.web.tests.csproj b/tests/bunit.web.tests/bunit.web.tests.csproj index 09885c8f4..2d486a751 100644 --- a/tests/bunit.web.tests/bunit.web.tests.csproj +++ b/tests/bunit.web.tests/bunit.web.tests.csproj @@ -1,7 +1,7 @@ - netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0 + net8.0;net9.0 Bunit Bunit.Web.Tests From abf185cdcc6bdb5a7e5763937868f7931093a511 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 2 Mar 2024 22:49:21 +0100 Subject: [PATCH 003/100] feat: Added Debugger hints --- .../Extensions/Internal/RefreshableElementCollection.cs | 2 ++ src/bunit.web/Rendering/RenderedComponent.cs | 3 +++ src/bunit.web/Rendering/RenderedFragment.cs | 2 ++ .../TestDoubles/NavigationManager/FakeNavigationManager.cs | 2 ++ .../TestDoubles/NavigationManager/NavigationHistory.cs | 5 ++++- 5 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/bunit.web/Extensions/Internal/RefreshableElementCollection.cs b/src/bunit.web/Extensions/Internal/RefreshableElementCollection.cs index 83854d8ee..e2d3ce62d 100644 --- a/src/bunit.web/Extensions/Internal/RefreshableElementCollection.cs +++ b/src/bunit.web/Extensions/Internal/RefreshableElementCollection.cs @@ -1,8 +1,10 @@ using System.Collections; +using System.Diagnostics; using AngleSharp.Dom; namespace Bunit; +[DebuggerDisplay("Selector={cssSelector}, AutoRefresh={enableAutoRefresh}")] internal sealed class RefreshableElementCollection : IRefreshableElementCollection { private readonly IRenderedFragment renderedFragment; diff --git a/src/bunit.web/Rendering/RenderedComponent.cs b/src/bunit.web/Rendering/RenderedComponent.cs index 009b7b13a..9ec4204a2 100644 --- a/src/bunit.web/Rendering/RenderedComponent.cs +++ b/src/bunit.web/Rendering/RenderedComponent.cs @@ -1,6 +1,9 @@ +using System.Diagnostics; + namespace Bunit.Rendering; /// +[DebuggerDisplay("Component={typeof(TComponent).Name,nq},RenderCount={RenderCount}")] internal sealed class RenderedComponent : RenderedFragment, IRenderedComponent where TComponent : IComponent { diff --git a/src/bunit.web/Rendering/RenderedFragment.cs b/src/bunit.web/Rendering/RenderedFragment.cs index 7f4e03df1..cb9f52fe7 100644 --- a/src/bunit.web/Rendering/RenderedFragment.cs +++ b/src/bunit.web/Rendering/RenderedFragment.cs @@ -1,9 +1,11 @@ +using System.Diagnostics; using AngleSharp.Diffing.Core; using AngleSharp.Dom; namespace Bunit.Rendering; /// +[DebuggerDisplay("Rendered:{RenderCount}")] internal class RenderedFragment : IRenderedFragment { [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by TestServiceProvider, disposed by it.")] diff --git a/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs b/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs index 12c9e7bdb..e8ccf1190 100644 --- a/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs +++ b/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using Bunit.Rendering; using Microsoft.AspNetCore.Components.Routing; @@ -9,6 +10,7 @@ namespace Bunit.TestDoubles; /// Represents a fake that captures calls to /// for testing purposes. ///
+[DebuggerDisplay("Current Uri: {Uri}, History Count: {History.Count}")] public sealed class FakeNavigationManager : NavigationManager { private readonly TestContextBase testContextBase; diff --git a/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs b/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs index 513cfddfc..ea0067680 100644 --- a/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs +++ b/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs @@ -1,12 +1,13 @@ +using System.Diagnostics; using System.Text.Json; using Microsoft.AspNetCore.Components.Routing; -using Microsoft.AspNetCore.Components.WebAssembly.Authentication; namespace Bunit.TestDoubles; /// /// Represents a navigation to a with a set of specific navigation . /// +[DebuggerDisplay("Uri={Uri}, NavigationState={State}, HasException={HasException}")] public sealed record NavigationHistory { /// @@ -33,6 +34,8 @@ public sealed record NavigationHistory /// public Exception? Exception { get; } + private bool HasException => Exception is not null; + /// /// Initializes a new instance of the class. /// From 344448fd63916434efb1825861be42dc3e33f7eb Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 5 May 2023 07:49:10 +0200 Subject: [PATCH 004/100] feat: remove Snapshop API --- MIGRATION.md | 7 + .../components/bunit.docs.samples.csproj | 36 +----- .../tests/xunit/VerifyMarkupExamples.cs | 68 ---------- docs/site/docs/verification/verify-markup.md | 51 +------- .../Asserting/DiffAssertExtensions.cs | 63 --------- .../Asserting/DiffChangeAssertException.cs | 33 ----- src/bunit.web/Asserting/HtmlEqualException.cs | 1 - .../ShouldBeAdditionAssertExtensions.cs | 79 ------------ .../ShouldBeRemovalAssertExtensions.cs | 78 ------------ .../ShouldBeTextChangeAssertExtensions.cs | 120 ------------------ src/bunit.web/IRenderedFragment.cs | 23 ---- src/bunit.web/Rendering/RenderedFragment.cs | 41 ------ .../BlazorE2E/AddRemoveChildComponents.razor | 1 - .../AsyncEventHandlerComponent.razor | 2 - .../BlazorE2E/ElementRefComponent.razor | 1 - .../TwoRendersTwoChanges.razor | 2 - .../Asserting/DiffAssertExtensionsTest.cs | 66 ---------- .../JSInterop/BunitJSObjectReferenceTest.cs | 6 - 18 files changed, 9 insertions(+), 669 deletions(-) create mode 100644 MIGRATION.md delete mode 100644 src/bunit.web/Asserting/DiffAssertExtensions.cs delete mode 100644 src/bunit.web/Asserting/DiffChangeAssertException.cs delete mode 100644 src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs delete mode 100644 src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs delete mode 100644 src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs delete mode 100644 tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 000000000..ac6b11983 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,7 @@ +# Migration Guide `v1` to `v2` +This document describes the changes that need to be made to migrate from bUnit 1.x to 2.x. + +## Removal of `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods +The `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods have been removed from `IRenderedComponent`. There is no one-to-one replacement for these methods, but the general idea is to select the HTML in question via `Find` and assert against that. + +Alternatively, the `IRenderFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. \ No newline at end of file diff --git a/docs/samples/components/bunit.docs.samples.csproj b/docs/samples/components/bunit.docs.samples.csproj index aa97c0fe7..248c2e787 100644 --- a/docs/samples/components/bunit.docs.samples.csproj +++ b/docs/samples/components/bunit.docs.samples.csproj @@ -1,47 +1,13 @@ - netstandard2.0;net5.0;net6.0;net7.0;net8.0;net9.0 - latest - 3.0 + net8.0;net.9.0 Bunit.Docs.Samples enable CA1014,NU5104 false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docs/samples/tests/xunit/VerifyMarkupExamples.cs b/docs/samples/tests/xunit/VerifyMarkupExamples.cs index 5788ceba0..0c6be470d 100644 --- a/docs/samples/tests/xunit/VerifyMarkupExamples.cs +++ b/docs/samples/tests/xunit/VerifyMarkupExamples.cs @@ -59,72 +59,4 @@ public void FindAndFindAll() Assert.Equal(2, tableCells.Count); Assert.All(tableCells, td => td.HasAttribute("style")); } - - [Fact] - public void GetChangesSinceFirstRenderTest() - { - var cut = RenderComponent(); - - // Act - increment the counter - cut.Find("button").Click(); - - // Assert - find differences between first render and click - var diffs = cut.GetChangesSinceFirstRender(); - - // Only expect there to be one change - var diff = diffs.ShouldHaveSingleChange(); - // and that change should be a text - // change to "Current count: 1" - diff.ShouldBeTextChange("Current count: 1"); - } - - [Fact] - public void GetChangesSinceX() - { - // Arrange - var cut = RenderComponent(); - var inputField = cut.Find("input"); - - // Add first item - inputField.Change("First item"); - inputField.KeyUp(key: "Enter"); - - // Assert that first item was added correctly - var diffs = cut.GetChangesSinceFirstRender(); - diffs.ShouldHaveSingleChange() - .ShouldBeAddition("
  • First item
  • "); - - // Save snapshot of current DOM nodes - cut.SaveSnapshot(); - - // Add a second item - inputField.Change("Second item"); - inputField.KeyUp(key: "Enter"); - - // Assert that both first and second item was added - // since the first render - diffs = cut.GetChangesSinceFirstRender(); - diffs.ShouldHaveChanges( - diff => diff.ShouldBeAddition("
  • First item
  • "), - diff => diff.ShouldBeAddition("
  • Second item
  • ") - ); - - // Assert that only the second item was added - // since the call to SaveSnapshot() - diffs = cut.GetChangesSinceSnapshot(); - diffs.ShouldHaveSingleChange() - .ShouldBeAddition("
  • Second item
  • "); - - // Save snapshot again of current DOM nodes - cut.SaveSnapshot(); - - // Click last item to remove it from list - cut.Find("li:last-child").Click(); - - // Assert that the second item was removed - // since the call to SaveSnapshot() - diffs = cut.GetChangesSinceSnapshot(); - diffs.ShouldHaveSingleChange() - .ShouldBeRemoval("
  • Second item
  • "); - } } \ No newline at end of file diff --git a/docs/site/docs/verification/verify-markup.md b/docs/site/docs/verification/verify-markup.md index 54d02678d..4df913022 100644 --- a/docs/site/docs/verification/verify-markup.md +++ b/docs/site/docs/verification/verify-markup.md @@ -120,55 +120,6 @@ The semantic HTML comparer can be customized to make a test case even more stabl Learn more about the customization options on the page. -## Finding expected differences - -It can sometimes be easier to verify that an expected change, and only that change, has occurred in the rendered markup than it can be to specify how all the rendered markup should look after re-rendering. - -bUnit comes with a number of ways for finding lists of `IDiff`; the representation of a difference between two HTML fragments. All of these are direct methods or extension methods on the type or on the `INode` or `INodeList` types: - -- method on . This method returns a list of differences since the initial first render of a component. -- and methods on . These two methods combined make it possible to get a list of differences between the last time the method was called and the time a call to the method is placed. -- `CompareTo()` methods from for the , `INode`, and `INodeList` types. These methods return a list of differences between the two input HTML fragments. - -In addition to this, there are a number of experimental assertion helpers for `IDiff` and `IEnumerable`, making it easier and more concise to declare your assertions. - -Let's look at a few examples of using the assertion helpers. In the first one, we will use the `` component listed below: - -[!code-razor[Counter.razor](../../../samples/components/Counter.razor)] - -Here is an example of using the method: - -[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=67&end=79&highlight=7,10,13)] - -This is what happens in the test: - -- On line 8, is used to get a list of differences. -- On line 11, the `ShouldHaveSingleChange()` method is used to verify that there is only one change found. -- On line 14, the `ShouldBeTextChange()` method is used to verify that the single `IDiff` is a text change. - -Testing a more **complex life cycle of a component** can be done more easily using the and methods along with a host of other assert helpers. - -This example tests the `` component listed below. The component allows you to add new items to the checklist by typing into the input field and hitting the `enter` key. Items can be removed from the list again by clicking on them. - -[!code-razor[CheckList.razor](../../../samples/components/CheckList.razor)] - -To test the end-to-end life cycle of adding and removing items from the `` component, do the following: - -[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=85&end=126)] - -This is what happens in the test: - -1. First the component is rendered and the input field is found. -2. The first item is added through the input field. -3. The , `ShouldHaveSingleChange()` and `ShouldBeAddition()` methods are used to verify that the item was correctly added. -4. The is used to save a snapshot of current DOM nodes internally in the `cut`. This reduces the number of diffs found in the following steps, simplifying verification. -5. A second item is added to the check list. -6. Two verifications are performed at this point, one using the method which finds two changes, and one using the method, which finds a single change. The first is only done for illustrative purposes. -7. A new snapshot is saved, replacing the previous one with another call to the method. -8. Finally the last item in the list is found and clicked, and the method is used to find the changes, a single diff, which is verified as a removal of the second item. - -As mentioned earlier, the `IDiff` assertion helpers are still experimental. Any feedback and suggestions for improvements should be directed to the [related issue](https://github.com/egil/bUnit/issues/84) on GitHub. - ## Verification of raw markup To access the rendered markup of a component, just use the property on . This holds the *raw* HTML from the component as a `string`. @@ -182,4 +133,4 @@ To get the markup as a string, do the following: [!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=16&end=19&highlight=3)] -Standard string assertions can be performed against the markup string, such as checking whether it contains a value or is empty. \ No newline at end of file +Standard string assertions can be performed against the markup string, such as checking whether it contains a value or is empty. diff --git a/src/bunit.web/Asserting/DiffAssertExtensions.cs b/src/bunit.web/Asserting/DiffAssertExtensions.cs deleted file mode 100644 index 6a41a9547..000000000 --- a/src/bunit.web/Asserting/DiffAssertExtensions.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Globalization; -using AngleSharp.Diffing.Core; -using Bunit.Asserting; - -namespace Bunit; - -/// -/// A collection of assert extensions and generic assert extensions. -/// -public static class DiffAssertExtensions -{ - /// - /// Verifies that a collection of s contains exactly one . - /// - /// The collection to be inspected. - /// The expected single in the collection. - public static IDiff ShouldHaveSingleChange(this IEnumerable diffs) - { - ArgumentNullException.ThrowIfNull(diffs); - - var diffsArray = diffs.ToArray(); - - if (diffsArray.Length != 1) - throw new ActualExpectedAssertException( - actual: diffsArray.Length.ToString(CultureInfo.InvariantCulture), - expected: "1", - actualText: "Actual changes", - expectedText: "Expected changes", - message: "There were more than one change"); - - return diffsArray[0]; - } - - /// - /// Verifies that a collection of s contains exactly a given number of elements, which - /// meet the criteria provided by the inspectors. - /// - /// The collection to be inspected. - /// The inspectors, which inspect each in turn. - /// The total number of inspectors must exactly match the number of s in the collection. - public static void ShouldHaveChanges(this IEnumerable diffs, params Action[] diffInspectors) - { - ArgumentNullException.ThrowIfNull(diffs); - ArgumentNullException.ThrowIfNull(diffInspectors); - - var diffsArray = diffs.ToArray(); - - if (diffsArray.Length != diffInspectors.Length) - throw new ActualExpectedAssertException( - actual: diffsArray.Length.ToString(CultureInfo.InvariantCulture), - expected: diffInspectors.Length.ToString(CultureInfo.InvariantCulture), - actualText: "Actual changes", - expectedText: "Expected changes", - message: "The actual number of changes does not match the expected."); - - var index = 0; - foreach (var diff in diffsArray) - { - diffInspectors[index](diff); - index++; - } - } -} diff --git a/src/bunit.web/Asserting/DiffChangeAssertException.cs b/src/bunit.web/Asserting/DiffChangeAssertException.cs deleted file mode 100644 index ff6820685..000000000 --- a/src/bunit.web/Asserting/DiffChangeAssertException.cs +++ /dev/null @@ -1,33 +0,0 @@ -using AngleSharp.Diffing.Core; -using Bunit.Asserting; - -namespace Bunit; - -/// -/// Represents an diff change assertion that has failed. -/// -[Serializable] -public sealed class DiffChangeAssertException : ActualExpectedAssertException -{ - /// - /// Initializes a new instance of the class. - /// - /// The actual change. - /// The expected change. - /// An error message explaining the context of the assertion. - public DiffChangeAssertException(DiffResult actual, DiffResult expected, string message) - : base(PrintDiffResult(actual), PrintDiffResult(expected), "Actual change", "Expected change", message) - { - } - - private static string PrintDiffResult(DiffResult result) => result switch - { - DiffResult.Different => "Changed", - DiffResult.Missing => "Removed", - DiffResult.Unexpected => "Added", - _ => throw new InvalidOperationException("Unknown DiffResult type"), - }; - - private DiffChangeAssertException(SerializationInfo serializationInfo, StreamingContext streamingContext) - : base(serializationInfo, streamingContext) { } -} diff --git a/src/bunit.web/Asserting/HtmlEqualException.cs b/src/bunit.web/Asserting/HtmlEqualException.cs index 541d752ce..437a08b18 100644 --- a/src/bunit.web/Asserting/HtmlEqualException.cs +++ b/src/bunit.web/Asserting/HtmlEqualException.cs @@ -1,6 +1,5 @@ using AngleSharp; using AngleSharp.Diffing.Core; -using Bunit; using Bunit.Asserting; namespace Bunit; diff --git a/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs b/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs deleted file mode 100644 index bcf8df9ba..000000000 --- a/src/bunit.web/Asserting/ShouldBeAdditionAssertExtensions.cs +++ /dev/null @@ -1,79 +0,0 @@ -using AngleSharp.Diffing.Core; -using AngleSharp.Dom; -using Bunit.Rendering; - -namespace Bunit; - -/// -/// A set of addition diff assert extensions. -/// -public static class ShouldBeAdditionAssertExtensions -{ - /// - /// Verifies that the is an addition, - /// i.e. that one or more nodes have been added, and verifies that the additions are equal - /// to the markup specified in the input. - /// - /// The change to verify. - /// The expected additions to verify against. - /// A custom user message to display in case the verification fails. - public static void ShouldBeAddition(this IDiff actualChange, string expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedChange); - if (actualChange is not UnexpectedNodeDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Unexpected, "The change was not an addition."); - - INodeList expected; - if (actual.Test.Node.GetHtmlParser() is BunitHtmlParser parser) - { - expected = parser.Parse(expectedChange); - } - else - { - using var newParser = new BunitHtmlParser(); - expected = newParser.Parse(expectedChange); - } - - ShouldBeAddition(actualChange, expected, userMessage); - } - - /// - /// Verifies that the is an addition, - /// i.e. that one or more nodes have been added, and verifies that the additions are equal - /// to the rendered markup from the . - /// - /// The change to verify. - /// The expected additions to verify against. - /// A custom user message to display in case the verification fails. - public static void ShouldBeAddition(this IDiff actualChange, IRenderedFragment expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(expectedChange); - ShouldBeAddition(actualChange, expectedChange.Nodes, userMessage); - } - - /// - /// Verifies that the is an addition, - /// i.e. that one or more nodes have been added, and verifies that the additions are equal - /// to the nodes. - /// - /// The change to verify. - /// The expected additions to verify against. - /// A custom user message to display in case the verification fails. - public static void ShouldBeAddition(this IDiff actualChange, INodeList expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedChange); - if (actualChange is not UnexpectedNodeDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Unexpected, "The change was not an addition."); - - var comparer = actual.Test.Node.GetHtmlComparer(); - - var diffs = comparer.Compare(expectedChange, actual.Test.Node.AsEnumerable()).ToList(); - - if (diffs.Count != 0) - { - throw new HtmlEqualException(diffs, expectedChange, actual.Test.Node, userMessage); - } - } -} diff --git a/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs b/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs deleted file mode 100644 index d37cc6f52..000000000 --- a/src/bunit.web/Asserting/ShouldBeRemovalAssertExtensions.cs +++ /dev/null @@ -1,78 +0,0 @@ -using AngleSharp.Diffing.Core; -using AngleSharp.Dom; -using Bunit.Rendering; - -namespace Bunit; - -/// -/// A set of removal diff assert extensions. -/// -public static class ShouldBeRemovalAssertExtensions -{ - /// - /// Verifies that the is an removal, - /// i.e. that one or more nodes have been removed, and verifies that the removed nodes are equal - /// to the markup specified in the input. - /// - /// The change to verify. - /// The expected removal to verify against. - /// A custom user message to display in case the verification fails. - public static void ShouldBeRemoval(this IDiff actualChange, string expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedChange); - if (actualChange is not MissingNodeDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Missing, "The change was not an removal."); - - INodeList expected; - if (actual.Control.Node.GetHtmlParser() is BunitHtmlParser parser) - { - expected = parser.Parse(expectedChange); - } - else - { - using var newParser = new BunitHtmlParser(); - expected = newParser.Parse(expectedChange); - } - - ShouldBeRemoval(actualChange, expected, userMessage); - } - - /// - /// Verifies that the is an removal, - /// i.e. that one or more nodes have been removed, and verifies that the removed nodes are equal - /// to the rendered markup from the . - /// - /// The change to verify. - /// The expected removal to verify against. - /// A custom user message to display in case the verification fails. - public static void ShouldBeRemoval(this IDiff actualChange, IRenderedFragment expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(expectedChange); - ShouldBeRemoval(actualChange, expectedChange.Nodes, userMessage); - } - - /// - /// Verifies that the is an removal, - /// i.e. that one or more nodes have been removed, and verifies that the removed nodes are equal - /// to the nodes. - /// - /// The change to verify. - /// The expected removal to verify against. - /// A custom user message to display in case the verification fails. - public static void ShouldBeRemoval(this IDiff actualChange, INodeList expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedChange); - if (actualChange is not MissingNodeDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Missing, "The change was not an removal."); - - var comparer = actual.Control.Node.GetHtmlComparer(); - var diffs = comparer.Compare(expectedChange, new[] { actual.Control.Node }).ToList(); - - if (diffs.Count != 0) - { - throw new HtmlEqualException(diffs, expectedChange, actual.Control.Node, userMessage); - } - } -} diff --git a/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs b/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs deleted file mode 100644 index da270c64c..000000000 --- a/src/bunit.web/Asserting/ShouldBeTextChangeAssertExtensions.cs +++ /dev/null @@ -1,120 +0,0 @@ -using AngleSharp.Diffing.Core; -using AngleSharp.Dom; -using Bunit.Asserting; -using Bunit.Rendering; - -namespace Bunit; - -/// -/// Verification helpers for text. -/// -public static class ShouldBeTextChangeAssertExtensions -{ - /// - /// Verifies that a list of diffs contains only a single change, and that change is a change to a text node. - /// - /// The list of diffs to verify against. - /// The expected text change. - /// A custom error message to show if the verification fails. - public static void ShouldHaveSingleTextChange(this IEnumerable diffs, string expectedChange, string? userMessage = null) - { - DiffAssertExtensions.ShouldHaveSingleChange(diffs).ShouldBeTextChange(expectedChange, userMessage); - } - - /// - /// Verifies that a diff is a change to a text node. - /// - /// The diff to verify. - /// The expected text change. - /// A custom error message to show if the verification fails. - public static void ShouldBeTextChange(this IDiff actualChange, string expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedChange); - if (actualChange is not NodeDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Different, "The change was not a text change."); - - INodeList expected; - if (actual.Control.Node.GetHtmlParser() is BunitHtmlParser parser) - { - expected = parser.Parse(expectedChange); - } - else - { - using var newParser = new BunitHtmlParser(); - expected = newParser.Parse(expectedChange); - } - ShouldBeTextChange(actualChange, expected, userMessage); - } - - /// - /// Verifies that a diff is a change to a text node. - /// - /// The diff to verify. - /// The rendered fragment containing the expected text change. - /// A custom error message to show if the verification fails. - public static void ShouldBeTextChange(this IDiff actualChange, IRenderedFragment expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(expectedChange); - ShouldBeTextChange(actualChange, expectedChange.Nodes, userMessage); - } - - /// - /// Verifies that a diff is a change to a text node. - /// - /// The diff to verify. - /// The node list containing the expected text change. - /// A custom error message to show if the verification fails. - public static void ShouldBeTextChange(this IDiff actualChange, INodeList expectedChange, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedChange); - if (actualChange is not NodeDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Different, "The change was not a text change."); - - var comparer = actual.Control.Node.GetHtmlComparer(); - - var diffs = comparer.Compare(expectedChange, new[] { actual.Test.Node }).ToList(); - - if (diffs.Count != 0) - { - throw new HtmlEqualException(diffs, expectedChange, actual.Test.Node, userMessage); - } - } - - /// - /// Verifies that the diff is a change to the value of the specific attribute (). - /// - /// The actual change that has happened. - /// The expected name of the changed attribute. - /// The expected value of the changed attribute. - /// A custom user message to show when the verification fails. - public static void ShouldBeAttributeChange(this IDiff actualChange, string expectedAttrName, string expectedAttrValue, string? userMessage = null) - { - ArgumentNullException.ThrowIfNull(actualChange); - ArgumentNullException.ThrowIfNull(expectedAttrName); - ArgumentNullException.ThrowIfNull(expectedAttrValue); - if (actualChange is not AttrDiff actual) - throw new DiffChangeAssertException(actualChange.Result, DiffResult.Different, "The change was not a attribute change."); - - if (!expectedAttrName.Equals(actual.Test.Attribute.Name, StringComparison.Ordinal)) - { - throw new ActualExpectedAssertException( - actual.Test.Attribute.Name, - expectedAttrName, - "Actual attribute name", - "Expected attribute name", - userMessage ?? "The name of the changed attribute does not match the expected name."); - } - - if (!expectedAttrValue.Equals(actual.Test.Attribute.Value, StringComparison.Ordinal)) - { - throw new ActualExpectedAssertException( - actual.Test.Attribute.Value, - expectedAttrValue, - "Actual attribute value", - "Expected attribute value", - userMessage ?? "The value of the changed attribute does not match the expected value."); - } - } -} diff --git a/src/bunit.web/IRenderedFragment.cs b/src/bunit.web/IRenderedFragment.cs index 38d87e179..dcb6a0514 100644 --- a/src/bunit.web/IRenderedFragment.cs +++ b/src/bunit.web/IRenderedFragment.cs @@ -23,27 +23,4 @@ public interface IRenderedFragment : IRenderedFragmentBase /// on the HTML markup from the rendered fragment/component. ///
    INodeList Nodes { get; } - - /// - /// Performs a comparison of the markup produced by the initial rendering of the - /// fragment or component under test with the current rendering of the fragment - /// or component under test. - /// - /// A list of differences found. - IReadOnlyList GetChangesSinceFirstRender(); - - /// - /// Performs a comparison of the markup produced by the rendering of the - /// fragment or component under test at the time the was called - /// with the current rendering of the fragment or component under test. - /// - /// A list of differences found. - IReadOnlyList GetChangesSinceSnapshot(); - - /// - /// Saves the markup from the current rendering of the fragment or component under test. - /// Use the method later to get the difference between - /// the snapshot and the rendered markup at that time. - /// - void SaveSnapshot(); } diff --git a/src/bunit.web/Rendering/RenderedFragment.cs b/src/bunit.web/Rendering/RenderedFragment.cs index cb9f52fe7..e643e58d4 100644 --- a/src/bunit.web/Rendering/RenderedFragment.cs +++ b/src/bunit.web/Rendering/RenderedFragment.cs @@ -12,16 +12,7 @@ internal class RenderedFragment : IRenderedFragment private readonly BunitHtmlParser htmlParser; private readonly object markupAccessLock = new(); private string markup = string.Empty; - private string? snapshotMarkup; - - private INodeList? firstRenderNodes; private INodeList? latestRenderNodes; - private INodeList? snapshotNodes; - - /// - /// Gets the first rendered markup. - /// - protected string FirstRenderMarkup { get; private set; } = string.Empty; /// public event EventHandler? OnAfterRender; @@ -87,34 +78,6 @@ internal RenderedFragment(int componentId, IServiceProvider service) htmlParser = Services.GetRequiredService(); } - /// - public IReadOnlyList GetChangesSinceFirstRender() - { - if (firstRenderNodes is null) - firstRenderNodes = htmlParser.Parse(FirstRenderMarkup); - - return Nodes.CompareTo(firstRenderNodes); - } - - /// - public IReadOnlyList GetChangesSinceSnapshot() - { - if (snapshotMarkup is null) - throw new InvalidOperationException($"No snapshot exists to compare with. Call {nameof(SaveSnapshot)}() to create one."); - - if (snapshotNodes is null) - snapshotNodes = htmlParser.Parse(snapshotMarkup); - - return Nodes.CompareTo(snapshotNodes); - } - - /// - public void SaveSnapshot() - { - snapshotNodes = null; - snapshotMarkup = Markup; - } - void IRenderedFragmentBase.OnRender(RenderEvent renderEvent) { if (IsDisposed) @@ -170,9 +133,6 @@ protected void UpdateMarkup(RenderTreeFrameDictionary framesCollection) // markup string can be stored in a CPUs register and not // get updated when another CPU changes the string. Volatile.Write(ref markup, newMarkup); - - if (RenderCount == 1) - FirstRenderMarkup = newMarkup; } } @@ -211,6 +171,5 @@ protected virtual void Dispose(bool disposing) IsDisposed = true; markup = string.Empty; OnAfterRender = null; - FirstRenderMarkup = string.Empty; } } diff --git a/tests/bunit.testassets/BlazorE2E/AddRemoveChildComponents.razor b/tests/bunit.testassets/BlazorE2E/AddRemoveChildComponents.razor index 1c05a7166..6b3634fcd 100644 --- a/tests/bunit.testassets/BlazorE2E/AddRemoveChildComponents.razor +++ b/tests/bunit.testassets/BlazorE2E/AddRemoveChildComponents.razor @@ -1,4 +1,3 @@ -@using System.Collections.Generic Child components follow. diff --git a/tests/bunit.testassets/BlazorE2E/AsyncEventHandlerComponent.razor b/tests/bunit.testassets/BlazorE2E/AsyncEventHandlerComponent.razor index cd5edf022..b91cc888a 100644 --- a/tests/bunit.testassets/BlazorE2E/AsyncEventHandlerComponent.razor +++ b/tests/bunit.testassets/BlazorE2E/AsyncEventHandlerComponent.razor @@ -1,5 +1,3 @@ -@using System.Threading.Tasks -
    @state diff --git a/tests/bunit.testassets/BlazorE2E/ElementRefComponent.razor b/tests/bunit.testassets/BlazorE2E/ElementRefComponent.razor index 36a003b48..5a2316837 100644 --- a/tests/bunit.testassets/BlazorE2E/ElementRefComponent.razor +++ b/tests/bunit.testassets/BlazorE2E/ElementRefComponent.razor @@ -1,4 +1,3 @@ -@using Microsoft.JSInterop @inject IJSRuntime JSRuntime

    Element capture

    diff --git a/tests/bunit.testassets/SampleComponents/TwoRendersTwoChanges.razor b/tests/bunit.testassets/SampleComponents/TwoRendersTwoChanges.razor index 697bc608d..b4ce14dfe 100644 --- a/tests/bunit.testassets/SampleComponents/TwoRendersTwoChanges.razor +++ b/tests/bunit.testassets/SampleComponents/TwoRendersTwoChanges.razor @@ -1,5 +1,3 @@ -@using System.Threading.Tasks -
    @state diff --git a/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs b/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs deleted file mode 100644 index 6f0de3ade..000000000 --- a/tests/bunit.web.tests/Asserting/DiffAssertExtensionsTest.cs +++ /dev/null @@ -1,66 +0,0 @@ -using AngleSharp.Diffing.Core; -using Bunit.Asserting; - -namespace Bunit; - -public class DiffAssertExtensionsTest -{ - [Fact(DisplayName = "ShouldHaveSingleChange throws when input is null")] - public void Test001() - { - IReadOnlyList? diffs = null; - Exception? exception = null; - - try - { - DiffAssertExtensions.ShouldHaveSingleChange(diffs!); - } - catch (Exception ex) - { - exception = ex; - } - - exception.ShouldBeOfType(); - } - - [Theory(DisplayName = "ShouldHaveSingleChange throws when input length not exactly 1")] - [MemberData(nameof(GetDiffLists))] - public void Test002(IReadOnlyList diffs) - { - Exception? exception = null; - - try - { - diffs.ShouldHaveSingleChange(); - } - catch (Exception ex) - { - exception = ex; - } - - exception.ShouldBeOfType(); - } - - [Fact(DisplayName = "ShouldHaveSingleChange returns the single diff in input when there is only one")] - public void Test003() - { - var input = new[] { Substitute.For() }; - - var output = input.ShouldHaveSingleChange(); - - output.ShouldBe(input[0]); - } - - public static IEnumerable GetDiffLists() - { - yield return new object[] { Array.Empty() }; - yield return new object[] - { - new IDiff[] - { - Substitute.For(), - Substitute.For(), - }, - }; - } -} diff --git a/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs b/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs index 2e2e29e1f..2bfe5efb1 100644 --- a/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs +++ b/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs @@ -1,9 +1,3 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using AutoFixture.Xunit2; using Bunit.JSInterop.InvocationHandlers.Implementation; using Microsoft.JSInterop.Implementation; From 59f840cb879abfa254ccfcf9ef6f999eb17bb0f8 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 5 May 2023 10:01:54 +0200 Subject: [PATCH 005/100] V2 enumerable internal (#1057) * refactor: Move EnumerableExtensions to usage and made it internal * refactor: Decrease visibility oof LoggerHelperExtensions * add: Documentation for migration --- MIGRATION.md | 19 ++++++++++++++++++- .../Extensions/LoggerHelperExtensions.cs | 2 +- .../Extensions/EnumerableExtensions.cs | 4 ++-- 3 files changed, 21 insertions(+), 4 deletions(-) rename src/{bunit.core => bunit.web}/Extensions/EnumerableExtensions.cs (75%) diff --git a/MIGRATION.md b/MIGRATION.md index ac6b11983..e47004cd5 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -4,4 +4,21 @@ This document describes the changes that need to be made to migrate from bUnit 1 ## Removal of `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods The `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods have been removed from `IRenderedComponent`. There is no one-to-one replacement for these methods, but the general idea is to select the HTML in question via `Find` and assert against that. -Alternatively, the `IRenderFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. \ No newline at end of file +Alternatively, the `IRenderFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. + +## Removal of `IsNullOrEmpty` extension method on `IEnumerable` and `CreateLogger` on `IserviceProvider` +The `IsNullOrEmpty` extension method on `IEnumerable` has been removed, as well as the `CreateLogger` extension method on `IServiceProvider`. These extension methods are pretty common and conflict with other libraries. These methods can be recreated like this: + +```csharp +public static class Extensions +{ + public static bool IsNullOrEmpty(this IEnumerable enumerable) + => enumerable == null || !enumerable.Any(); + + public static ILogger CreateLogger(this IServiceProvider serviceProvider) + { + var loggerFactory = serviceProvider.GetRequiredService() ?? NullLoggerFactory.Instance; + return loggerFactory.CreateLogger(); + } +} +``` \ No newline at end of file diff --git a/src/bunit.core/Extensions/LoggerHelperExtensions.cs b/src/bunit.core/Extensions/LoggerHelperExtensions.cs index 2efe28ac3..de90249e2 100644 --- a/src/bunit.core/Extensions/LoggerHelperExtensions.cs +++ b/src/bunit.core/Extensions/LoggerHelperExtensions.cs @@ -6,7 +6,7 @@ namespace Bunit.Extensions; /// /// Helper extension methods for getting a logger. /// -public static class LoggerHelperExtensions +internal static class LoggerHelperExtensions { /// /// Creates a logger from the registered in the . diff --git a/src/bunit.core/Extensions/EnumerableExtensions.cs b/src/bunit.web/Extensions/EnumerableExtensions.cs similarity index 75% rename from src/bunit.core/Extensions/EnumerableExtensions.cs rename to src/bunit.web/Extensions/EnumerableExtensions.cs index ca454840f..f6a501858 100644 --- a/src/bunit.core/Extensions/EnumerableExtensions.cs +++ b/src/bunit.web/Extensions/EnumerableExtensions.cs @@ -3,10 +3,10 @@ namespace Bunit.Extensions; /// /// Helper methods for working with . /// -public static class EnumerableExtensions +internal static class EnumerableExtensions { /// - /// Returns true if the numerable is null or empty. + /// Returns true if the enumerable is null or empty. /// public static bool IsNullOrEmpty([NotNullWhen(false)] this IEnumerable? enumerable) { From ee1ebfaadb644b74bd6399a28629883cb6ecc4b7 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 2 Mar 2024 23:37:54 +0100 Subject: [PATCH 006/100] feat: Merge bunit.core and bunit.web to bunit --- Directory.Build.props | 4 +- MIGRATION.md | 5 +- README.md | 6 +- benchmark/Directory.Build.props | 14 --- .../bunit.benchmarks.assets/Counter.razor | 21 ---- .../bunit.benchmarks.assets.csproj | 18 ---- benchmark/bunit.benchmarks/Benchmark.cs | 14 --- benchmark/bunit.benchmarks/BenchmarkBase.cs | 47 -------- benchmark/bunit.benchmarks/Program.cs | 6 -- .../bunit.benchmarks/bunit.benchmarks.csproj | 20 ---- bunit.sln | 56 ++-------- .../mstest/bunit.docs.mstest.samples.csproj | 2 +- .../nunit/bunit.docs.nunit.samples.csproj | 2 +- .../razor/bunit.docs.razor.samples.csproj | 2 +- .../xunit/bunit.docs.xunit.samples.csproj | 2 +- ...RenderedFragmentWaitForHelperExtensions.cs | 100 ------------------ src/bunit.core/InternalsVisibleTo.cs | 2 - src/bunit.core/bunit.core.csproj | 29 ----- src/bunit.web/InternalsVisibleTo.cs | 1 - src/bunit.web/bunit.web.csproj | 61 ----------- .../ActualExpectedAssertException.cs | 0 .../Asserting/AssertionMethodAttribute.cs | 0 .../Asserting/CompareToExtensions.cs | 0 .../FocusAsyncAssertJSInteropExtensions.cs | 0 ...ocusOnNavigateAssertJSInteropExtensions.cs | 0 .../Asserting/HtmlEqualException.cs | 0 .../JSInvokeCountExpectedException.cs | 0 .../Asserting/JSRuntimeAssertExtensions.cs | 0 .../MarkupMatchesAssertExtensions.cs | 0 .../ConditionalComponentFactory.cs | 0 ...actory{TComponent,TSubstituteComponent}.cs | 0 .../InstanceComponentFactory{TComponent}.cs | 0 .../StubComponentFactory.cs | 0 .../TypeBasedComponentFactory{TComponent}.cs | 0 .../ComponentFactoryCollection.cs | 0 .../ComponentParameter.cs | 0 .../ComponentParameterCollection.cs | 0 .../ComponentParameterCollectionBuilder.cs | 0 .../ComponentParameterFactory.cs | 0 .../Diffing/BlazorDiffingHelpers.cs | 0 .../Diffing/DiffMarkupFormatter.cs | 0 .../Diffing/HtmlComparer.cs | 0 .../ClipboardEventDispatchExtensions.cs | 0 .../DetailsElementEventDispatchExtensions.cs | 0 .../DialogEventDispatchExtensions.cs | 0 .../DragEventDispatchExtensions.cs | 0 .../FocusEventDispatchExtensions.cs | 0 .../GeneralEventDispatchExtensions.cs | 0 .../InputEventDispatchExtensions.cs | 0 .../EventDispatchExtensions/Key.cs | 0 .../KeyboardEventDispatchExtensions.cs | 0 .../MediaEventDispatchExtensions.cs | 0 .../MissingEventHandlerException.cs | 0 .../MouseEventDispatchExtensions.cs | 0 .../PointerEventDispatchExtensions.cs | 0 .../ProgressEventDispatchExtensions.cs | 0 .../TouchEventDispatchExtensions.cs | 0 .../TriggerEventDispatchExtensions.cs | 0 .../Extensions/BlazorExtensions.cs | 0 .../ComponentFactoryCollectionExtensions.cs | 0 .../Extensions/ElementNotFoundException.cs | 0 .../ElementRemovedFromDomException.cs | 0 .../Extensions/EnumerableExtensions.cs | 0 .../IRefreshableElementCollection.cs | 0 .../Extensions/InputFile/BUnitBrowserFile.cs | 0 .../Extensions/InputFile/InputFileContent.cs | 0 .../InputFile/InputFileExtensions.cs | 0 .../Internal/AngleSharpExtensions.cs | 0 .../Internal/AngleSharpWrapperExtensions.cs | 0 .../Internal/CssSelectorElementFactory.cs | 0 .../Internal/RefreshableElementCollection.cs | 0 .../Extensions/LoggerHelperExtensions.cs | 0 .../Extensions/NodePrintExtensions.cs | 0 .../RenderedComponentRenderExtensions.cs | 0 .../Extensions/RenderedFragmentExtensions.cs | 0 .../RenderedFragmentInvokeAsyncExtensions.cs | 0 ...tubComponentFactoryCollectionExtensions.cs | 0 .../TestContextBaseRenderExtensions.cs | 0 .../Extensions/TestRendererExtensions.cs | 0 .../TestServiceProviderExtensions.cs | 0 ...WaitForHelperExtensions.WaitForElement.cs} | 2 +- ...entWaitForHelperExtensions.WaitForState.cs | 100 ++++++++++++++++++ .../WaitForHelpers/WaitForAssertionHelper.cs | 0 .../WaitForHelpers/WaitForElementHelper.cs | 0 .../WaitForHelpers/WaitForElementsHelper.cs | 0 .../WaitForHelpers/WaitForFailedException.cs | 0 .../WaitForHelpers/WaitForHelper.cs | 0 .../WaitForHelperLoggerExtensions.cs | 0 .../WaitForHelpers/WaitForStateHelper.cs | 0 .../IComponentFactory.cs | 0 .../IRenderedComponent.cs | 0 .../IRenderedComponentBase.cs | 0 src/{bunit.web => bunit}/IRenderedFragment.cs | 0 .../IRenderedFragmentBase.cs | 0 src/bunit/InternalsVisibleTo.cs | 1 + .../JSInterop/BunitJSInterop.cs | 0 .../BunitJSInteropSetupExtensions.cs | 0 .../BunitJSInteropSetupExtensions.net5.cs | 0 .../JSInterop/BunitJSModuleInterop.cs | 0 .../Implementation/BunitJSObjectReference.cs | 0 .../Implementation/BunitJSRuntime.cs | 0 .../Implementation/BunitJSRuntime.net5.cs | 0 .../Implementation/JSRuntimeExtensions.cs | 0 .../FocusAsyncInvocationHandler.cs | 0 .../Implementation/FocusOnNavigateHandler.cs | 0 .../InputFileInvocationHandler.cs | 0 .../JSObjectReferenceInvocationHandler.cs | 0 ...eModeJSObjectReferenceInvocationHandler.cs | 0 ...isableNavigationPromptInvocationHandler.cs | 0 ...EnableNavigationPromptInvocationHandler.cs | 0 .../VirtualizeJSRuntimeInvocationHandler.cs | 0 .../JSRuntimeInvocationHandler.cs | 0 ...JSRuntimeInvocationHandlerBase{TResult}.cs | 0 .../JSRuntimeInvocationHandler{TResult}.cs | 0 .../JSInterop/InvocationMatcher.cs | 0 .../JSInterop/JSRuntimeInvocation.cs | 0 .../JSRuntimeInvocationDictionary.cs | 0 .../JSInterop/JSRuntimeMode.cs | 0 .../JSRuntimeUnhandledInvocationException.cs | 0 .../ParameterException.cs | 0 .../Rendering/BunitComponentActivator.cs | 0 .../Rendering/BunitHtmlParser.cs | 0 .../Rendering/ComponentDisposedException.cs | 0 .../Rendering/ComponentNotFoundException.cs | 0 .../Rendering/FragmentContainer.cs | 0 .../Rendering/IRenderedComponentActivator.cs | 0 .../Rendering/ITestRenderer.cs | 0 .../Internal/BunitHtmlParserHelpers.cs | 0 .../Rendering/Internal/Htmlizer.cs | 0 .../Rendering/RenderEvent.cs | 0 .../Rendering/RenderTreeFrameDictionary.cs | 0 .../Rendering/RenderedComponent.cs | 0 .../Rendering/RenderedComponentActivator.cs | 0 .../Rendering/RenderedFragment.cs | 0 .../Rendering/RootComponent.cs | 0 .../Rendering/RootRenderTree.cs | 0 .../Rendering/RootRenderTreeRegistration.cs | 0 .../Rendering/TestRenderer.cs | 0 .../Rendering/TestRendererLoggerExtensions.cs | 0 .../UnknownEventHandlerIdException.cs | 0 .../Rendering/WebTestRenderer.cs | 0 src/{bunit.web => bunit}/TestContext.cs | 0 src/{bunit.core => bunit}/TestContextBase.cs | 0 .../TestContextWrapper.cs | 0 .../Authorization/AuthorizationState.cs | 0 .../FakeAuthenticationStateProvider.cs | 0 .../FakeAuthorizationExtensions.cs | 0 .../FakeAuthorizationPolicyProvider.cs | 0 .../Authorization/FakeAuthorizationService.cs | 0 .../MissingFakeAuthorizationException.cs | 0 .../PlaceholderAuthenticationStateProvider.cs | 0 .../PlaceholderAuthorizationService.cs | 0 .../Authorization/TestAuthorizationContext.cs | 0 .../Authorization/TestPolicyRequirement.cs | 0 .../CapturedParameterView{TComponent}.cs | 0 .../ComponentDoubleBase{TComponent}.cs | 0 .../Components/ParameterNotFoundException.cs | 0 .../Components/Stub{TComponent}.cs | 0 .../ErrorBoundary/BunitErrorBoundaryLogger.cs | 0 .../MissingMockHttpClientException.cs | 0 .../HttpClient/PlaceholderHttpClient.cs | 0 .../MissingMockStringLocalizationException.cs | 0 .../PlaceholderStringLocalization.cs | 0 .../FakeNavigationInterception.cs | 0 .../FakeNavigationManager.cs | 0 .../FakeSignOutSessionStateManager.cs | 0 .../NavigationManager/NavigationHistory.cs | 0 .../NavigationManager/NavigationState.cs | 0 .../FakePersistentComponentState.cs | 0 .../FakePersistentComponentStateStore.cs | 0 .../TestContextBaseExtensions.cs | 0 .../BunitScrollToLocationHash.cs | 0 .../FakeWebAssemblyHostEnvironment.cs | 0 .../TestServiceProvider.cs | 0 src/bunit/bunit.csproj | 32 +++++- src/src.sln | 60 ----------- .../bunit.generators.tests.csproj | 2 +- .../Assembly.cs | 0 .../CompareToDiffingExtensionsTest.cs | 0 .../JSRuntimeAssertExtensionsTest.cs | 0 .../MarkupMatchesAssertExtensionsTest.cs | 0 .../MarkupMatchesAssertExtensionsTest.net5.cs | 0 .../Asserting/MarkupMatchesTests.razor | 0 .../BlazorE2E/ComponentRenderingTest.cs | 0 .../ConditionalComponentFactoryTest.cs | 0 .../GenericComponentFactoryTest.cs | 0 .../InstanceComponentFactoryTest.cs | 0 .../StubComponentFactoryTest.cs | 0 .../TypeBasedComponentFactoryTest.cs | 0 ...omponentParameterCollectionBuilderTests.cs | 0 ...onentParameterCollectionBuilderTests.razor | 0 .../ComponentParameterCollectionTest.cs | 0 .../ComponentParameterFactoryTest.cs | 0 .../ClipboardEventDispatchExtensionsTest.cs | 0 ...ilsElementEventDispatcherExtensionsTest.cs | 0 .../DragEventDispatchExtensionsTest.cs | 0 .../EventDispatchExtensionsTest.cs | 0 .../FocusEventDispatchExtensionsTest.cs | 0 .../GeneralEventDispatchExtensionsTest.cs | 0 .../InputEventDispatchExtensionsTest.cs | 0 .../EventDispatchExtensions/KeyTest.cs | 0 .../KeyboardEventDispatchExtensionsTest.cs | 0 .../MediaEventDispatchExtensionsTest.cs | 0 .../MouseEventDispatchExtensionsTest.cs | 0 .../PointerEventDispatchExtensionsTest.cs | 0 .../ProgressEventDispatchExtensionsTest.cs | 0 .../TouchEventDispatchExtensionsTest.cs | 0 .../TriggerEventSpy.cs | 0 .../WheelEventDispatchExtensionsTest.cs | 0 .../Extensions/InputFile/InputFileTests.cs | 0 .../RefreshableQueryCollectionTest.cs | 0 .../RefreshingWrappedElementTest.cs | 0 .../RenderedComponentRenderExtensionsTest.cs | 0 ...tForElementsHelperExtensions.Async.Test.cs | 0 ...mentWaitForElementsHelperExtensionsTest.cs | 0 ...eredFragmentWaitForHelperExtensionsTest.cs | 0 .../JSInterop/BunitJSInteropTest.cs | 0 .../JSInterop/BunitJSInteropTest.net5.cs | 0 .../JSInterop/BunitJSObjectReferenceTest.cs | 0 .../FocusAsyncInvocationHandlerTest.cs | 0 .../FocusOnNavigateHandlerTest.cs | 0 ...irtualizeJSRuntimeInvocationHandlerTest.cs | 0 .../JSInterop/JSRuntimeInvocationTest.cs | 0 ...RuntimeUnhandledInvocationExceptionTest.cs | 0 ...meUnhandledInvocationExceptionTest.net5.cs | 0 .../Rendering/BunitComponentActivatorTest.cs | 0 .../Rendering/BunitHtmlParserTest.cs | 0 .../Rendering/ComponentParameterTest.cs | 0 .../Rendering/Internal/HtmlizerTests.cs | 0 .../Rendering/Internal/HtmlizerTests.net5.cs | 0 .../Rendering/RenderedComponentTest.cs | 0 .../Rendering/RenderedFragmentTest.cs | 0 .../Rendering/RootRenderTreeTest.cs | 0 .../Rendering/TestRendererTest.cs | 0 .../Rendering/TestRendererTest.net5.cs | 0 .../ShouldlyExtensions.cs | 0 .../TestContextBaseTest.cs | 0 .../TestContextBaseTest.net5.cs | 0 .../TestContextTest.cs | 0 .../TestContextTest.net6.cs | 0 .../Authorization/AuthorizationTest.cs | 0 .../FakeAuthenticationStateProviderTest.cs | 0 .../FakeAuthorizationPolicyProviderTest.cs | 0 .../FakeAuthorizationServiceTest.cs | 0 .../TestAuthorizationContextTest.cs | 0 .../Components/CapturedParameterViewTest.cs | 0 .../Components/ComponentDoubleBaseTest.cs | 0 .../TestDoubles/Components/StubTest.cs | 0 .../FakeSignOutSessionStateManagerTest.cs | 0 .../FakeWebAssemblyHostEnvironmentTest.cs | 0 .../FakeNavigationInterceptionTest.cs | 0 .../FakeNavigationManagerTest.cs | 0 .../FakePersistentComponentStateTest.cs | 0 .../TestServiceProviderTest.cs | 0 .../JSRuntimeInvocationAssertionHelpers.cs | 0 .../TestUtilities/MockingHelpers.cs | 0 .../_Imports.razor | 0 .../bunit.tests.csproj} | 5 +- .../xunit.runner.json | 0 .../bunit.web.query.tests.csproj | 3 +- tests/bunit.web.tests/bunit.web.tests.csproj | 25 ----- tests/bunit.web.tests/xunit.runner.json | 4 - 262 files changed, 154 insertions(+), 492 deletions(-) delete mode 100644 benchmark/Directory.Build.props delete mode 100644 benchmark/bunit.benchmarks.assets/Counter.razor delete mode 100644 benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj delete mode 100644 benchmark/bunit.benchmarks/Benchmark.cs delete mode 100644 benchmark/bunit.benchmarks/BenchmarkBase.cs delete mode 100644 benchmark/bunit.benchmarks/Program.cs delete mode 100644 benchmark/bunit.benchmarks/bunit.benchmarks.csproj delete mode 100644 src/bunit.core/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs delete mode 100644 src/bunit.core/InternalsVisibleTo.cs delete mode 100644 src/bunit.core/bunit.core.csproj delete mode 100644 src/bunit.web/InternalsVisibleTo.cs delete mode 100644 src/bunit.web/bunit.web.csproj rename src/{bunit.core => bunit}/Asserting/ActualExpectedAssertException.cs (100%) rename src/{bunit.core => bunit}/Asserting/AssertionMethodAttribute.cs (100%) rename src/{bunit.web => bunit}/Asserting/CompareToExtensions.cs (100%) rename src/{bunit.web => bunit}/Asserting/FocusAsyncAssertJSInteropExtensions.cs (100%) rename src/{bunit.web => bunit}/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs (100%) rename src/{bunit.web => bunit}/Asserting/HtmlEqualException.cs (100%) rename src/{bunit.web => bunit}/Asserting/JSInvokeCountExpectedException.cs (100%) rename src/{bunit.web => bunit}/Asserting/JSRuntimeAssertExtensions.cs (100%) rename src/{bunit.web => bunit}/Asserting/MarkupMatchesAssertExtensions.cs (100%) rename src/{bunit.core => bunit}/ComponentFactories/ConditionalComponentFactory.cs (100%) rename src/{bunit.core => bunit}/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs (100%) rename src/{bunit.core => bunit}/ComponentFactories/InstanceComponentFactory{TComponent}.cs (100%) rename src/{bunit.web => bunit}/ComponentFactories/StubComponentFactory.cs (100%) rename src/{bunit.core => bunit}/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs (100%) rename src/{bunit.core => bunit}/ComponentFactoryCollection.cs (100%) rename src/{bunit.core => bunit}/ComponentParameter.cs (100%) rename src/{bunit.core => bunit}/ComponentParameterCollection.cs (100%) rename src/{bunit.core => bunit}/ComponentParameterCollectionBuilder.cs (100%) rename src/{bunit.core => bunit}/ComponentParameterFactory.cs (100%) rename src/{bunit.web => bunit}/Diffing/BlazorDiffingHelpers.cs (100%) rename src/{bunit.web => bunit}/Diffing/DiffMarkupFormatter.cs (100%) rename src/{bunit.web => bunit}/Diffing/HtmlComparer.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/ClipboardEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/DialogEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/DragEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/FocusEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/GeneralEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/InputEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/Key.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/KeyboardEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/MediaEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/MissingEventHandlerException.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/MouseEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/PointerEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/ProgressEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/TouchEventDispatchExtensions.cs (100%) rename src/{bunit.web => bunit}/EventDispatchExtensions/TriggerEventDispatchExtensions.cs (100%) rename src/{bunit.core => bunit}/Extensions/BlazorExtensions.cs (100%) rename src/{bunit.core => bunit}/Extensions/ComponentFactoryCollectionExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/ElementNotFoundException.cs (100%) rename src/{bunit.web => bunit}/Extensions/ElementRemovedFromDomException.cs (100%) rename src/{bunit.web => bunit}/Extensions/EnumerableExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/IRefreshableElementCollection.cs (100%) rename src/{bunit.web => bunit}/Extensions/InputFile/BUnitBrowserFile.cs (100%) rename src/{bunit.web => bunit}/Extensions/InputFile/InputFileContent.cs (100%) rename src/{bunit.web => bunit}/Extensions/InputFile/InputFileExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/Internal/AngleSharpExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/Internal/AngleSharpWrapperExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/Internal/CssSelectorElementFactory.cs (100%) rename src/{bunit.web => bunit}/Extensions/Internal/RefreshableElementCollection.cs (100%) rename src/{bunit.core => bunit}/Extensions/LoggerHelperExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/NodePrintExtensions.cs (100%) rename src/{bunit.core => bunit}/Extensions/RenderedComponentRenderExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/RenderedFragmentExtensions.cs (100%) rename src/{bunit.core => bunit}/Extensions/RenderedFragmentInvokeAsyncExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/StubComponentFactoryCollectionExtensions.cs (100%) rename src/{bunit.core => bunit}/Extensions/TestContextBaseRenderExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/TestRendererExtensions.cs (100%) rename src/{bunit.web => bunit}/Extensions/TestServiceProviderExtensions.cs (100%) rename src/{bunit.web/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs => bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs} (99%) create mode 100644 src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs rename src/{bunit.core => bunit}/Extensions/WaitForHelpers/WaitForAssertionHelper.cs (100%) rename src/{bunit.web => bunit}/Extensions/WaitForHelpers/WaitForElementHelper.cs (100%) rename src/{bunit.web => bunit}/Extensions/WaitForHelpers/WaitForElementsHelper.cs (100%) rename src/{bunit.core => bunit}/Extensions/WaitForHelpers/WaitForFailedException.cs (100%) rename src/{bunit.core => bunit}/Extensions/WaitForHelpers/WaitForHelper.cs (100%) rename src/{bunit.core => bunit}/Extensions/WaitForHelpers/WaitForHelperLoggerExtensions.cs (100%) rename src/{bunit.core => bunit}/Extensions/WaitForHelpers/WaitForStateHelper.cs (100%) rename src/{bunit.core => bunit}/IComponentFactory.cs (100%) rename src/{bunit.web => bunit}/IRenderedComponent.cs (100%) rename src/{bunit.core => bunit}/IRenderedComponentBase.cs (100%) rename src/{bunit.web => bunit}/IRenderedFragment.cs (100%) rename src/{bunit.core => bunit}/IRenderedFragmentBase.cs (100%) create mode 100644 src/bunit/InternalsVisibleTo.cs rename src/{bunit.web => bunit}/JSInterop/BunitJSInterop.cs (100%) rename src/{bunit.web => bunit}/JSInterop/BunitJSInteropSetupExtensions.cs (100%) rename src/{bunit.web => bunit}/JSInterop/BunitJSInteropSetupExtensions.net5.cs (100%) rename src/{bunit.web => bunit}/JSInterop/BunitJSModuleInterop.cs (100%) rename src/{bunit.web => bunit}/JSInterop/Implementation/BunitJSObjectReference.cs (100%) rename src/{bunit.web => bunit}/JSInterop/Implementation/BunitJSRuntime.cs (100%) rename src/{bunit.web => bunit}/JSInterop/Implementation/BunitJSRuntime.net5.cs (100%) rename src/{bunit.web => bunit}/JSInterop/Implementation/JSRuntimeExtensions.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler{TResult}.cs (100%) rename src/{bunit.web => bunit}/JSInterop/InvocationMatcher.cs (100%) rename src/{bunit.web => bunit}/JSInterop/JSRuntimeInvocation.cs (100%) rename src/{bunit.web => bunit}/JSInterop/JSRuntimeInvocationDictionary.cs (100%) rename src/{bunit.web => bunit}/JSInterop/JSRuntimeMode.cs (100%) rename src/{bunit.web => bunit}/JSInterop/JSRuntimeUnhandledInvocationException.cs (100%) rename src/{bunit.core => bunit}/ParameterException.cs (100%) rename src/{bunit.core => bunit}/Rendering/BunitComponentActivator.cs (100%) rename src/{bunit.web => bunit}/Rendering/BunitHtmlParser.cs (100%) rename src/{bunit.core => bunit}/Rendering/ComponentDisposedException.cs (100%) rename src/{bunit.core => bunit}/Rendering/ComponentNotFoundException.cs (100%) rename src/{bunit.core => bunit}/Rendering/FragmentContainer.cs (100%) rename src/{bunit.core => bunit}/Rendering/IRenderedComponentActivator.cs (100%) rename src/{bunit.core => bunit}/Rendering/ITestRenderer.cs (100%) rename src/{bunit.web => bunit}/Rendering/Internal/BunitHtmlParserHelpers.cs (100%) rename src/{bunit.web => bunit}/Rendering/Internal/Htmlizer.cs (100%) rename src/{bunit.core => bunit}/Rendering/RenderEvent.cs (100%) rename src/{bunit.core => bunit}/Rendering/RenderTreeFrameDictionary.cs (100%) rename src/{bunit.web => bunit}/Rendering/RenderedComponent.cs (100%) rename src/{bunit.web => bunit}/Rendering/RenderedComponentActivator.cs (100%) rename src/{bunit.web => bunit}/Rendering/RenderedFragment.cs (100%) rename src/{bunit.core => bunit}/Rendering/RootComponent.cs (100%) rename src/{bunit.core => bunit}/Rendering/RootRenderTree.cs (100%) rename src/{bunit.core => bunit}/Rendering/RootRenderTreeRegistration.cs (100%) rename src/{bunit.core => bunit}/Rendering/TestRenderer.cs (100%) rename src/{bunit.core => bunit}/Rendering/TestRendererLoggerExtensions.cs (100%) rename src/{bunit.core => bunit}/Rendering/UnknownEventHandlerIdException.cs (100%) rename src/{bunit.web => bunit}/Rendering/WebTestRenderer.cs (100%) rename src/{bunit.web => bunit}/TestContext.cs (100%) rename src/{bunit.core => bunit}/TestContextBase.cs (100%) rename src/{bunit.web => bunit}/TestContextWrapper.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/AuthorizationState.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/FakeAuthorizationExtensions.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/FakeAuthorizationService.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/MissingFakeAuthorizationException.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/PlaceholderAuthorizationService.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/TestAuthorizationContext.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Authorization/TestPolicyRequirement.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Components/CapturedParameterView{TComponent}.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Components/ParameterNotFoundException.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Components/Stub{TComponent}.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/HttpClient/MissingMockHttpClientException.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/HttpClient/PlaceholderHttpClient.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Localization/MissingMockStringLocalizationException.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/Localization/PlaceholderStringLocalization.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/NavigationInterception/FakeNavigationInterception.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/NavigationManager/FakeNavigationManager.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/NavigationManager/NavigationHistory.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/NavigationManager/NavigationState.cs (100%) rename src/{bunit.core => bunit}/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs (100%) rename src/{bunit.core => bunit}/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs (100%) rename src/{bunit.core => bunit}/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs (100%) rename src/{bunit.web => bunit}/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs (100%) rename src/{bunit.core => bunit}/TestServiceProvider.cs (100%) delete mode 100644 src/src.sln rename tests/{bunit.web.tests => bunit.tests}/Assembly.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Asserting/CompareToDiffingExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Asserting/JSRuntimeAssertExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Asserting/MarkupMatchesAssertExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Asserting/MarkupMatchesTests.razor (100%) rename tests/{bunit.web.tests => bunit.tests}/BlazorE2E/ComponentRenderingTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentFactories/ConditionalComponentFactoryTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentFactories/GenericComponentFactoryTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentFactories/InstanceComponentFactoryTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/ComponentFactories/StubComponentFactoryTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentFactories/TypeBasedComponentFactoryTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentParameterCollectionBuilderTests.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentParameterCollectionBuilderTests.razor (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentParameterCollectionTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ComponentParameterFactoryTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/EventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/KeyTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/TriggerEventSpy.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Extensions/InputFile/InputFileTests.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Extensions/RefreshableQueryCollectionTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Extensions/RefreshingWrappedElementTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Extensions/RenderedComponentRenderExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/BunitJSInteropTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/BunitJSInteropTest.net5.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/BunitJSObjectReferenceTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/JSRuntimeInvocationTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Rendering/BunitComponentActivatorTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Rendering/BunitHtmlParserTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Rendering/ComponentParameterTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Rendering/Internal/HtmlizerTests.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Rendering/Internal/HtmlizerTests.net5.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Rendering/RenderedComponentTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/Rendering/RenderedFragmentTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Rendering/RootRenderTreeTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Rendering/TestRendererTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/Rendering/TestRendererTest.net5.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/ShouldlyExtensions.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/TestContextBaseTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/TestContextBaseTest.net5.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestContextTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestContextTest.net6.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Authorization/AuthorizationTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Authorization/TestAuthorizationContextTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Components/CapturedParameterViewTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Components/ComponentDoubleBaseTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/Components/StubTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/FakeSignOutSessionStateManagerTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/TestServiceProviderTest.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestUtilities/JSRuntimeInvocationAssertionHelpers.cs (100%) rename tests/{bunit.web.tests => bunit.tests}/TestUtilities/MockingHelpers.cs (100%) rename tests/{bunit.core.tests => bunit.tests}/_Imports.razor (100%) rename tests/{bunit.core.tests/bunit.core.tests.csproj => bunit.tests/bunit.tests.csproj} (78%) rename tests/{bunit.core.tests => bunit.tests}/xunit.runner.json (100%) delete mode 100644 tests/bunit.web.tests/bunit.web.tests.csproj delete mode 100644 tests/bunit.web.tests/xunit.runner.json diff --git a/Directory.Build.props b/Directory.Build.props index 6d933a4a7..aa67dc315 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -41,7 +41,7 @@ - + true @@ -52,7 +52,7 @@ + Condition="$(MSBuildProjectName) != 'bunit.template' AND $(MSBuildProjectName) != 'AngleSharpWrappers.Tests'"> diff --git a/MIGRATION.md b/MIGRATION.md index e47004cd5..142d55daa 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -21,4 +21,7 @@ public static class Extensions return loggerFactory.CreateLogger(); } } -``` \ No newline at end of file +``` + +## Merge of `bunit.core` and `bunit.web` +The `bunit.core` and `bunit.web` packages have been merged into a single `bunit` package. If you used either of these packages, you should remove them and install the `bunit` package instead. diff --git a/README.md b/README.md index a1f0bb490..ff3bbd61f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ [![GitHub tag](https://img.shields.io/github/v/tag/bUnit-dev/bUnit?include_prereleases&logo=github&style=flat-square)](https://github.com/bUnit-dev/bUnit/releases) -[![Nuget](https://img.shields.io/nuget/dt/bunit.core?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit/) +[![Nuget](https://img.shields.io/nuget/dt/bunit?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit/) [![Issues Open](https://img.shields.io/github/issues/bUnit-dev/bUnit.svg?style=flat-square&logo=github)](https://github.com/bUnit-dev/bUnit/issues) # bUnit - a testing library for Blazor components @@ -29,9 +29,7 @@ bUnit is available on NuGet in various incarnations. Most should just pick the [ | Name | Description | NuGet Download Link | | ----- | ----- | ---- | -| [bUnit](https://www.nuget.org/packages/bunit/) | Includes the bUnit.core and bUnit.web packages. | [![Nuget](https://img.shields.io/nuget/dt/bunit?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit/) | -| [bUnit.core](https://www.nuget.org/packages/bunit.core/) | Core library that enables rendering a Blazor component in a test context. | [![Nuget](https://img.shields.io/nuget/dt/bunit.core?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit.core/) | -| [bUnit.web](https://www.nuget.org/packages/bunit.web/) | Adds support for testing Blazor components for the web. This includes bUnit.core. | [![Nuget](https://img.shields.io/nuget/dt/bunit.web?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit.web/) | +| [bUnit](https://www.nuget.org/packages/bunit/) | Adds support for testing Blazor components. | [![Nuget](https://img.shields.io/nuget/dt/bunit?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit/) | | [bUnit.template](https://www.nuget.org/packages/bunit.template/) | Template, which currently creates xUnit-based bUnit test projects only. | [![Nuget](https://img.shields.io/nuget/dt/bunit.template?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit.template/) | | [bUnit.generators](https://www.nuget.org/packages/bunit.generators/)|Source code generators to minimize code setup in various situations.|[![Nuget](https://img.shields.io/nuget/dt/bunit.generators?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit.generators/)| | [bUnit.web.query](https://www.nuget.org/packages/bunit.web.query/)|bUnit implementation of testing-library.com's query APIs.|[![Nuget](https://img.shields.io/nuget/dt/bunit.web.query?logo=nuget&style=flat-square)](https://www.nuget.org/packages/bunit.web.query/)| diff --git a/benchmark/Directory.Build.props b/benchmark/Directory.Build.props deleted file mode 100644 index 62cb9cc94..000000000 --- a/benchmark/Directory.Build.props +++ /dev/null @@ -1,14 +0,0 @@ - - - - enable - 10.0 - enable - CA1014,NU5104 - false - - - full - true - - diff --git a/benchmark/bunit.benchmarks.assets/Counter.razor b/benchmark/bunit.benchmarks.assets/Counter.razor deleted file mode 100644 index 381411d2a..000000000 --- a/benchmark/bunit.benchmarks.assets/Counter.razor +++ /dev/null @@ -1,21 +0,0 @@ -@page "/counter" - -

    Counter - Example

    - -

    This is not the real counter example but a bit adopted to have more stuff in it.

    -
    - Look mum I am centered -
    - -

    Current count: @currentCount

    - - - -@code { - private int currentCount = 0; - - private void IncrementCount() - { - currentCount++; - } -} \ No newline at end of file diff --git a/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj b/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj deleted file mode 100644 index abc5199cd..000000000 --- a/benchmark/bunit.benchmarks.assets/bunit.benchmarks.assets.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - - diff --git a/benchmark/bunit.benchmarks/Benchmark.cs b/benchmark/bunit.benchmarks/Benchmark.cs deleted file mode 100644 index 343f305fa..000000000 --- a/benchmark/bunit.benchmarks/Benchmark.cs +++ /dev/null @@ -1,14 +0,0 @@ -using BenchmarkDotNet.Attributes; -using bunit.benchmarks.assets; - -namespace Bunit; - -[MemoryDiagnoser] -public class Benchmark : BenchmarkBase -{ - [Benchmark] - public IRenderedComponentBase RenderCounter() - { - return RenderComponent(); - } -} \ No newline at end of file diff --git a/benchmark/bunit.benchmarks/BenchmarkBase.cs b/benchmark/bunit.benchmarks/BenchmarkBase.cs deleted file mode 100644 index f45d26972..000000000 --- a/benchmark/bunit.benchmarks/BenchmarkBase.cs +++ /dev/null @@ -1,47 +0,0 @@ -using BenchmarkDotNet.Attributes; -using Bunit.Rendering; -using Microsoft.AspNetCore.Components; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging.Abstractions; - -namespace Bunit; - -public abstract class BenchmarkBase -{ - private static readonly ComponentParameterCollection EmptyParameter = new(); - private readonly ServiceCollection services = new(); - - protected TestRenderer Renderer { get; private set; } = default!; - - [GlobalSetup] - public void Setup() - { - RegisterServices(services); - - var serviceProvider = services.BuildServiceProvider(); - Renderer = new TestRenderer( - new RenderedComponentActivator(serviceProvider), - new TestServiceProvider(services), - new NullLoggerFactory()); - } - - [GlobalCleanup] - public void Cleanup() - { - InternalCleanup(); - Renderer.Dispose(); - } - - protected IRenderedComponentBase RenderComponent() - where TComponent : IComponent => - Renderer.RenderComponent(EmptyParameter); - - protected virtual void InternalCleanup() - { - } - - protected virtual void RegisterServices(IServiceCollection serviceCollection) - { - services.AddSingleton(); - } -} \ No newline at end of file diff --git a/benchmark/bunit.benchmarks/Program.cs b/benchmark/bunit.benchmarks/Program.cs deleted file mode 100644 index 18d11e89b..000000000 --- a/benchmark/bunit.benchmarks/Program.cs +++ /dev/null @@ -1,6 +0,0 @@ -// See https://aka.ms/new-console-template for more information - -using BenchmarkDotNet.Running; -using Bunit; - -BenchmarkSwitcher.FromAssembly(typeof(Benchmark).Assembly).RunAll(); diff --git a/benchmark/bunit.benchmarks/bunit.benchmarks.csproj b/benchmark/bunit.benchmarks/bunit.benchmarks.csproj deleted file mode 100644 index 1212e538f..000000000 --- a/benchmark/bunit.benchmarks/bunit.benchmarks.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - Exe - net8.0 - enable - false - - - - - - - - - - - - - diff --git a/bunit.sln b/bunit.sln index c39a1c1ba..117ccb6ea 100644 --- a/bunit.sln +++ b/bunit.sln @@ -31,20 +31,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".text", ".text", "{392FCD4E ProjectSection(SolutionItems) = preProject CHANGELOG.md = CHANGELOG.md README.md = README.md + MIGRATION.md = MIGRATION.md EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.core.tests", "tests\bunit.core.tests\bunit.core.tests.csproj", "{3A1486BF-1029-4E5B-A79B-2D36C8152240}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit", "src\bunit\bunit.csproj", "{1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.core", "src\bunit.core\bunit.core.csproj", "{0C51D12D-A562-4229-B653-78B14960345C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.web", "src\bunit.web\bunit.web.csproj", "{C91AE830-FFB5-49A9-A604-3F68B44EBCDC}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.template", "src\bunit.template\bunit.template.csproj", "{6127D121-9387-451B-B15D-8350A32D3001}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.web.tests", "tests\bunit.web.tests\bunit.web.tests.csproj", "{FC122F63-8B22-4BAE-B96A-7AF3194CD204}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.testassets", "tests\bunit.testassets\bunit.testassets.csproj", "{7972A80F-30DC-4EF4-9294-7D4DD2965882}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".workflows", ".workflows", "{3B2F3419-5336-4147-A212-E19091195203}" @@ -55,15 +48,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".workflows", ".workflows", .github\workflows\release.yml = .github\workflows\release.yml EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "benchmark", "benchmark", "{F6084D31-2A92-4794-A47E-A8F2254E6970}" - ProjectSection(SolutionItems) = preProject - benchmark\Directory.Build.props = benchmark\Directory.Build.props - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.benchmarks", "benchmark\bunit.benchmarks\bunit.benchmarks.csproj", "{9F7A0623-8294-4A5D-946F-70C481732AA5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.benchmarks.assets", "benchmark\bunit.benchmarks.assets\bunit.benchmarks.assets.csproj", "{3619481F-DF6F-4399-9FED-450EE545A19E}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.web.query", "src\bunit.web.query\bunit.web.query.csproj", "{0FF92169-7D8F-46A2-8327-A2F028CB426F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.web.query.tests", "tests\bunit.web.query.tests\bunit.web.query.tests.csproj", "{DE975A0C-0672-4248-913E-D267C1001801}" @@ -74,44 +58,23 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.generators.tests", "t EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.generators", "src\bunit.generators\bunit.generators.csproj", "{A7C6A2AA-FF8F-4ED1-8590-5324FC566059}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bunit.tests", "tests\bunit.tests\bunit.tests.csproj", "{56889DE7-5E66-4E9C-815B-CBCFC9961612}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {3A1486BF-1029-4E5B-A79B-2D36C8152240}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3A1486BF-1029-4E5B-A79B-2D36C8152240}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3A1486BF-1029-4E5B-A79B-2D36C8152240}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3A1486BF-1029-4E5B-A79B-2D36C8152240}.Release|Any CPU.Build.0 = Release|Any CPU {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0C51D12D-A562-4229-B653-78B14960345C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0C51D12D-A562-4229-B653-78B14960345C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0C51D12D-A562-4229-B653-78B14960345C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0C51D12D-A562-4229-B653-78B14960345C}.Release|Any CPU.Build.0 = Release|Any CPU - {C91AE830-FFB5-49A9-A604-3F68B44EBCDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C91AE830-FFB5-49A9-A604-3F68B44EBCDC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C91AE830-FFB5-49A9-A604-3F68B44EBCDC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C91AE830-FFB5-49A9-A604-3F68B44EBCDC}.Release|Any CPU.Build.0 = Release|Any CPU + {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Release|Any CPU.Build.0 = Release|Any CPU {6127D121-9387-451B-B15D-8350A32D3001}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6127D121-9387-451B-B15D-8350A32D3001}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FC122F63-8B22-4BAE-B96A-7AF3194CD204}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FC122F63-8B22-4BAE-B96A-7AF3194CD204}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FC122F63-8B22-4BAE-B96A-7AF3194CD204}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FC122F63-8B22-4BAE-B96A-7AF3194CD204}.Release|Any CPU.Build.0 = Release|Any CPU {7972A80F-30DC-4EF4-9294-7D4DD2965882}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7972A80F-30DC-4EF4-9294-7D4DD2965882}.Debug|Any CPU.Build.0 = Debug|Any CPU {7972A80F-30DC-4EF4-9294-7D4DD2965882}.Release|Any CPU.ActiveCfg = Release|Any CPU {7972A80F-30DC-4EF4-9294-7D4DD2965882}.Release|Any CPU.Build.0 = Release|Any CPU - {9F7A0623-8294-4A5D-946F-70C481732AA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9F7A0623-8294-4A5D-946F-70C481732AA5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9F7A0623-8294-4A5D-946F-70C481732AA5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9F7A0623-8294-4A5D-946F-70C481732AA5}.Release|Any CPU.Build.0 = Release|Any CPU - {3619481F-DF6F-4399-9FED-450EE545A19E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3619481F-DF6F-4399-9FED-450EE545A19E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3619481F-DF6F-4399-9FED-450EE545A19E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3619481F-DF6F-4399-9FED-450EE545A19E}.Release|Any CPU.Build.0 = Release|Any CPU {0FF92169-7D8F-46A2-8327-A2F028CB426F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0FF92169-7D8F-46A2-8327-A2F028CB426F}.Debug|Any CPU.Build.0 = Debug|Any CPU {0FF92169-7D8F-46A2-8327-A2F028CB426F}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -132,25 +95,24 @@ Global {A7C6A2AA-FF8F-4ED1-8590-5324FC566059}.Debug|Any CPU.Build.0 = Debug|Any CPU {A7C6A2AA-FF8F-4ED1-8590-5324FC566059}.Release|Any CPU.ActiveCfg = Release|Any CPU {A7C6A2AA-FF8F-4ED1-8590-5324FC566059}.Release|Any CPU.Build.0 = Release|Any CPU + {56889DE7-5E66-4E9C-815B-CBCFC9961612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {56889DE7-5E66-4E9C-815B-CBCFC9961612}.Debug|Any CPU.Build.0 = Debug|Any CPU + {56889DE7-5E66-4E9C-815B-CBCFC9961612}.Release|Any CPU.ActiveCfg = Release|Any CPU + {56889DE7-5E66-4E9C-815B-CBCFC9961612}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {3A1486BF-1029-4E5B-A79B-2D36C8152240} = {6EA09ED4-B714-4E6F-B0E1-4D987F8AE520} {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} - {0C51D12D-A562-4229-B653-78B14960345C} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} - {C91AE830-FFB5-49A9-A604-3F68B44EBCDC} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} {6127D121-9387-451B-B15D-8350A32D3001} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} - {FC122F63-8B22-4BAE-B96A-7AF3194CD204} = {6EA09ED4-B714-4E6F-B0E1-4D987F8AE520} {7972A80F-30DC-4EF4-9294-7D4DD2965882} = {6EA09ED4-B714-4E6F-B0E1-4D987F8AE520} - {9F7A0623-8294-4A5D-946F-70C481732AA5} = {F6084D31-2A92-4794-A47E-A8F2254E6970} - {3619481F-DF6F-4399-9FED-450EE545A19E} = {F6084D31-2A92-4794-A47E-A8F2254E6970} {0FF92169-7D8F-46A2-8327-A2F028CB426F} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} {DE975A0C-0672-4248-913E-D267C1001801} = {6EA09ED4-B714-4E6F-B0E1-4D987F8AE520} {AE3DFB52-2BF4-4806-AD82-7FB7B38AC17F} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} {09046981-D9EC-4295-8502-721AC54E1F12} = {6EA09ED4-B714-4E6F-B0E1-4D987F8AE520} {A7C6A2AA-FF8F-4ED1-8590-5324FC566059} = {9A2B3B34-D41C-43E8-BC7D-246BEBE48D59} + {56889DE7-5E66-4E9C-815B-CBCFC9961612} = {6EA09ED4-B714-4E6F-B0E1-4D987F8AE520} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {24106918-1C86-4769-BDA6-9C80E64CD260} diff --git a/docs/samples/tests/mstest/bunit.docs.mstest.samples.csproj b/docs/samples/tests/mstest/bunit.docs.mstest.samples.csproj index 2d6428b0b..4bfdc389b 100644 --- a/docs/samples/tests/mstest/bunit.docs.mstest.samples.csproj +++ b/docs/samples/tests/mstest/bunit.docs.mstest.samples.csproj @@ -14,7 +14,7 @@
    - + diff --git a/docs/samples/tests/nunit/bunit.docs.nunit.samples.csproj b/docs/samples/tests/nunit/bunit.docs.nunit.samples.csproj index a51a9ff84..0cd6ceefd 100644 --- a/docs/samples/tests/nunit/bunit.docs.nunit.samples.csproj +++ b/docs/samples/tests/nunit/bunit.docs.nunit.samples.csproj @@ -13,7 +13,7 @@ - + diff --git a/docs/samples/tests/razor/bunit.docs.razor.samples.csproj b/docs/samples/tests/razor/bunit.docs.razor.samples.csproj index 9dff4b342..54d2834b3 100644 --- a/docs/samples/tests/razor/bunit.docs.razor.samples.csproj +++ b/docs/samples/tests/razor/bunit.docs.razor.samples.csproj @@ -19,7 +19,7 @@ - + diff --git a/docs/samples/tests/xunit/bunit.docs.xunit.samples.csproj b/docs/samples/tests/xunit/bunit.docs.xunit.samples.csproj index 96ed4edf4..2d1b479f9 100644 --- a/docs/samples/tests/xunit/bunit.docs.xunit.samples.csproj +++ b/docs/samples/tests/xunit/bunit.docs.xunit.samples.csproj @@ -21,7 +21,7 @@ - + diff --git a/src/bunit.core/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs b/src/bunit.core/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs deleted file mode 100644 index 00a2ce7d2..000000000 --- a/src/bunit.core/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.Runtime.ExceptionServices; -using Bunit.Asserting; -using Bunit.Extensions.WaitForHelpers; - -namespace Bunit; - -/// -/// Helper methods dealing with async rendering during testing. -/// -public static class RenderedFragmentWaitForHelperExtensions -{ - /// - /// Wait until the provided action returns true, - /// or the is reached (default is one second). - /// - /// The is evaluated initially, and then each time - /// the renders. - /// - /// The render fragment or component to attempt to verify state against. - /// The predicate to invoke after each render, which must returns true when the desired state has been reached. - /// The maximum time to wait for the desired state. - /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. - /// - /// If a debugger is attached the timeout is set to , giving the possibility to debug without the timeout triggering. - /// - public static void WaitForState(this IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) - { - using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); - - try - { - waiter.WaitTask.GetAwaiter().GetResult(); - } - catch (AggregateException e) when (e.InnerExceptions.Count == 1) - { - ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw(); - } - } - - /// - /// Wait until the provided action returns true, - /// or the is reached (default is one second). - /// - /// The is evaluated initially, and then each time - /// the renders. - /// - /// The render fragment or component to attempt to verify state against. - /// The predicate to invoke after each render, which must returns true when the desired state has been reached. - /// The maximum time to wait for the desired state. - /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. - internal static async Task WaitForStateAsync(this IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) - { - using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); - - await waiter.WaitTask; - } - - /// - /// Wait until the provided passes (i.e. does not throw an - /// exception), or the is reached (default is one second). - /// - /// The is attempted initially, and then each time the renders. - /// - /// The rendered fragment to wait for renders from and assert against. - /// The verification or assertion to perform. - /// The maximum time to attempt the verification. - /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. - [AssertionMethod] - public static void WaitForAssertion(this IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) - { - using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); - - try - { - waiter.WaitTask.GetAwaiter().GetResult(); - } - catch (AggregateException e) when (e.InnerExceptions.Count == 1) - { - ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw(); - } - } - - /// - /// Wait until the provided passes (i.e. does not throw an - /// exception), or the is reached (default is one second). - /// - /// The is attempted initially, and then each time the renders. - /// - /// The rendered fragment to wait for renders from and assert against. - /// The verification or assertion to perform. - /// The maximum time to attempt the verification. - /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. - [AssertionMethod] - internal static async Task WaitForAssertionAsync(this IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) - { - using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); - - await waiter.WaitTask; - } -} diff --git a/src/bunit.core/InternalsVisibleTo.cs b/src/bunit.core/InternalsVisibleTo.cs deleted file mode 100644 index a07259efa..000000000 --- a/src/bunit.core/InternalsVisibleTo.cs +++ /dev/null @@ -1,2 +0,0 @@ -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bunit.Core.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001be6b1a2ca57b09b7040e2ab0993e515296ae22aef4031a4fe388a1336fe21f69c7e8610e9935de6ed18d94b5c98429f99ef62ce3d0af28a7088f856239368ea808ad4c448aa2a8075ed581f989f36ed0d0b8b1cfcaf1ff6a4506c8a99b7024b6eb56996d08e3c9c1cf5db59bff96fcc63ccad155ef7fc63aab6a69862437b6")] -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bunit.Web.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001be6b1a2ca57b09b7040e2ab0993e515296ae22aef4031a4fe388a1336fe21f69c7e8610e9935de6ed18d94b5c98429f99ef62ce3d0af28a7088f856239368ea808ad4c448aa2a8075ed581f989f36ed0d0b8b1cfcaf1ff6a4506c8a99b7024b6eb56996d08e3c9c1cf5db59bff96fcc63ccad155ef7fc63aab6a69862437b6")] diff --git a/src/bunit.core/bunit.core.csproj b/src/bunit.core/bunit.core.csproj deleted file mode 100644 index f50f7659f..000000000 --- a/src/bunit.core/bunit.core.csproj +++ /dev/null @@ -1,29 +0,0 @@ - - - - net8.0;net9.0 - Bunit - Bunit.Core - - - - bunit.core - bUnit.core - - bUnit.core is the base library that provides support for testing Blazor components. You need to install bUnit.web as well to test web-based Blazor components. - - - - - - - - - - - - - - - - diff --git a/src/bunit.web/InternalsVisibleTo.cs b/src/bunit.web/InternalsVisibleTo.cs deleted file mode 100644 index 8761816ad..000000000 --- a/src/bunit.web/InternalsVisibleTo.cs +++ /dev/null @@ -1 +0,0 @@ -[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bunit.Web.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001be6b1a2ca57b09b7040e2ab0993e515296ae22aef4031a4fe388a1336fe21f69c7e8610e9935de6ed18d94b5c98429f99ef62ce3d0af28a7088f856239368ea808ad4c448aa2a8075ed581f989f36ed0d0b8b1cfcaf1ff6a4506c8a99b7024b6eb56996d08e3c9c1cf5db59bff96fcc63ccad155ef7fc63aab6a69862437b6")] diff --git a/src/bunit.web/bunit.web.csproj b/src/bunit.web/bunit.web.csproj deleted file mode 100644 index 131657010..000000000 --- a/src/bunit.web/bunit.web.csproj +++ /dev/null @@ -1,61 +0,0 @@ - - - - net8.0;net9.0 - Bunit - Bunit.Web - - - - - - bunit.web - bUnit.web - - bUnit.web is the web specific parts of bUnit, that enables you to easily test and verify the output of Blazor (web) component. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/bunit.core/Asserting/ActualExpectedAssertException.cs b/src/bunit/Asserting/ActualExpectedAssertException.cs similarity index 100% rename from src/bunit.core/Asserting/ActualExpectedAssertException.cs rename to src/bunit/Asserting/ActualExpectedAssertException.cs diff --git a/src/bunit.core/Asserting/AssertionMethodAttribute.cs b/src/bunit/Asserting/AssertionMethodAttribute.cs similarity index 100% rename from src/bunit.core/Asserting/AssertionMethodAttribute.cs rename to src/bunit/Asserting/AssertionMethodAttribute.cs diff --git a/src/bunit.web/Asserting/CompareToExtensions.cs b/src/bunit/Asserting/CompareToExtensions.cs similarity index 100% rename from src/bunit.web/Asserting/CompareToExtensions.cs rename to src/bunit/Asserting/CompareToExtensions.cs diff --git a/src/bunit.web/Asserting/FocusAsyncAssertJSInteropExtensions.cs b/src/bunit/Asserting/FocusAsyncAssertJSInteropExtensions.cs similarity index 100% rename from src/bunit.web/Asserting/FocusAsyncAssertJSInteropExtensions.cs rename to src/bunit/Asserting/FocusAsyncAssertJSInteropExtensions.cs diff --git a/src/bunit.web/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs b/src/bunit/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs similarity index 100% rename from src/bunit.web/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs rename to src/bunit/Asserting/FocusOnNavigateAssertJSInteropExtensions.cs diff --git a/src/bunit.web/Asserting/HtmlEqualException.cs b/src/bunit/Asserting/HtmlEqualException.cs similarity index 100% rename from src/bunit.web/Asserting/HtmlEqualException.cs rename to src/bunit/Asserting/HtmlEqualException.cs diff --git a/src/bunit.web/Asserting/JSInvokeCountExpectedException.cs b/src/bunit/Asserting/JSInvokeCountExpectedException.cs similarity index 100% rename from src/bunit.web/Asserting/JSInvokeCountExpectedException.cs rename to src/bunit/Asserting/JSInvokeCountExpectedException.cs diff --git a/src/bunit.web/Asserting/JSRuntimeAssertExtensions.cs b/src/bunit/Asserting/JSRuntimeAssertExtensions.cs similarity index 100% rename from src/bunit.web/Asserting/JSRuntimeAssertExtensions.cs rename to src/bunit/Asserting/JSRuntimeAssertExtensions.cs diff --git a/src/bunit.web/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs similarity index 100% rename from src/bunit.web/Asserting/MarkupMatchesAssertExtensions.cs rename to src/bunit/Asserting/MarkupMatchesAssertExtensions.cs diff --git a/src/bunit.core/ComponentFactories/ConditionalComponentFactory.cs b/src/bunit/ComponentFactories/ConditionalComponentFactory.cs similarity index 100% rename from src/bunit.core/ComponentFactories/ConditionalComponentFactory.cs rename to src/bunit/ComponentFactories/ConditionalComponentFactory.cs diff --git a/src/bunit.core/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs b/src/bunit/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs similarity index 100% rename from src/bunit.core/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs rename to src/bunit/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs diff --git a/src/bunit.core/ComponentFactories/InstanceComponentFactory{TComponent}.cs b/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs similarity index 100% rename from src/bunit.core/ComponentFactories/InstanceComponentFactory{TComponent}.cs rename to src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs diff --git a/src/bunit.web/ComponentFactories/StubComponentFactory.cs b/src/bunit/ComponentFactories/StubComponentFactory.cs similarity index 100% rename from src/bunit.web/ComponentFactories/StubComponentFactory.cs rename to src/bunit/ComponentFactories/StubComponentFactory.cs diff --git a/src/bunit.core/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs b/src/bunit/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs similarity index 100% rename from src/bunit.core/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs rename to src/bunit/ComponentFactories/TypeBasedComponentFactory{TComponent}.cs diff --git a/src/bunit.core/ComponentFactoryCollection.cs b/src/bunit/ComponentFactoryCollection.cs similarity index 100% rename from src/bunit.core/ComponentFactoryCollection.cs rename to src/bunit/ComponentFactoryCollection.cs diff --git a/src/bunit.core/ComponentParameter.cs b/src/bunit/ComponentParameter.cs similarity index 100% rename from src/bunit.core/ComponentParameter.cs rename to src/bunit/ComponentParameter.cs diff --git a/src/bunit.core/ComponentParameterCollection.cs b/src/bunit/ComponentParameterCollection.cs similarity index 100% rename from src/bunit.core/ComponentParameterCollection.cs rename to src/bunit/ComponentParameterCollection.cs diff --git a/src/bunit.core/ComponentParameterCollectionBuilder.cs b/src/bunit/ComponentParameterCollectionBuilder.cs similarity index 100% rename from src/bunit.core/ComponentParameterCollectionBuilder.cs rename to src/bunit/ComponentParameterCollectionBuilder.cs diff --git a/src/bunit.core/ComponentParameterFactory.cs b/src/bunit/ComponentParameterFactory.cs similarity index 100% rename from src/bunit.core/ComponentParameterFactory.cs rename to src/bunit/ComponentParameterFactory.cs diff --git a/src/bunit.web/Diffing/BlazorDiffingHelpers.cs b/src/bunit/Diffing/BlazorDiffingHelpers.cs similarity index 100% rename from src/bunit.web/Diffing/BlazorDiffingHelpers.cs rename to src/bunit/Diffing/BlazorDiffingHelpers.cs diff --git a/src/bunit.web/Diffing/DiffMarkupFormatter.cs b/src/bunit/Diffing/DiffMarkupFormatter.cs similarity index 100% rename from src/bunit.web/Diffing/DiffMarkupFormatter.cs rename to src/bunit/Diffing/DiffMarkupFormatter.cs diff --git a/src/bunit.web/Diffing/HtmlComparer.cs b/src/bunit/Diffing/HtmlComparer.cs similarity index 100% rename from src/bunit.web/Diffing/HtmlComparer.cs rename to src/bunit/Diffing/HtmlComparer.cs diff --git a/src/bunit.web/EventDispatchExtensions/ClipboardEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/ClipboardEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/ClipboardEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/ClipboardEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/DetailsElementEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/DialogEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/DialogEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/DialogEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/DialogEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/DragEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/DragEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/DragEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/DragEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/FocusEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/FocusEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/FocusEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/FocusEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/GeneralEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/GeneralEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/GeneralEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/GeneralEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/InputEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/InputEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/InputEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/InputEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/Key.cs b/src/bunit/EventDispatchExtensions/Key.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/Key.cs rename to src/bunit/EventDispatchExtensions/Key.cs diff --git a/src/bunit.web/EventDispatchExtensions/KeyboardEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/KeyboardEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/KeyboardEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/KeyboardEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/MediaEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/MediaEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/MediaEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/MediaEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/MissingEventHandlerException.cs b/src/bunit/EventDispatchExtensions/MissingEventHandlerException.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/MissingEventHandlerException.cs rename to src/bunit/EventDispatchExtensions/MissingEventHandlerException.cs diff --git a/src/bunit.web/EventDispatchExtensions/MouseEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/MouseEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/MouseEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/MouseEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/PointerEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/PointerEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/PointerEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/PointerEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/ProgressEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/ProgressEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/ProgressEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/ProgressEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/TouchEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/TouchEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/TouchEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/TouchEventDispatchExtensions.cs diff --git a/src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs similarity index 100% rename from src/bunit.web/EventDispatchExtensions/TriggerEventDispatchExtensions.cs rename to src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs diff --git a/src/bunit.core/Extensions/BlazorExtensions.cs b/src/bunit/Extensions/BlazorExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/BlazorExtensions.cs rename to src/bunit/Extensions/BlazorExtensions.cs diff --git a/src/bunit.core/Extensions/ComponentFactoryCollectionExtensions.cs b/src/bunit/Extensions/ComponentFactoryCollectionExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/ComponentFactoryCollectionExtensions.cs rename to src/bunit/Extensions/ComponentFactoryCollectionExtensions.cs diff --git a/src/bunit.web/Extensions/ElementNotFoundException.cs b/src/bunit/Extensions/ElementNotFoundException.cs similarity index 100% rename from src/bunit.web/Extensions/ElementNotFoundException.cs rename to src/bunit/Extensions/ElementNotFoundException.cs diff --git a/src/bunit.web/Extensions/ElementRemovedFromDomException.cs b/src/bunit/Extensions/ElementRemovedFromDomException.cs similarity index 100% rename from src/bunit.web/Extensions/ElementRemovedFromDomException.cs rename to src/bunit/Extensions/ElementRemovedFromDomException.cs diff --git a/src/bunit.web/Extensions/EnumerableExtensions.cs b/src/bunit/Extensions/EnumerableExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/EnumerableExtensions.cs rename to src/bunit/Extensions/EnumerableExtensions.cs diff --git a/src/bunit.web/Extensions/IRefreshableElementCollection.cs b/src/bunit/Extensions/IRefreshableElementCollection.cs similarity index 100% rename from src/bunit.web/Extensions/IRefreshableElementCollection.cs rename to src/bunit/Extensions/IRefreshableElementCollection.cs diff --git a/src/bunit.web/Extensions/InputFile/BUnitBrowserFile.cs b/src/bunit/Extensions/InputFile/BUnitBrowserFile.cs similarity index 100% rename from src/bunit.web/Extensions/InputFile/BUnitBrowserFile.cs rename to src/bunit/Extensions/InputFile/BUnitBrowserFile.cs diff --git a/src/bunit.web/Extensions/InputFile/InputFileContent.cs b/src/bunit/Extensions/InputFile/InputFileContent.cs similarity index 100% rename from src/bunit.web/Extensions/InputFile/InputFileContent.cs rename to src/bunit/Extensions/InputFile/InputFileContent.cs diff --git a/src/bunit.web/Extensions/InputFile/InputFileExtensions.cs b/src/bunit/Extensions/InputFile/InputFileExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/InputFile/InputFileExtensions.cs rename to src/bunit/Extensions/InputFile/InputFileExtensions.cs diff --git a/src/bunit.web/Extensions/Internal/AngleSharpExtensions.cs b/src/bunit/Extensions/Internal/AngleSharpExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/Internal/AngleSharpExtensions.cs rename to src/bunit/Extensions/Internal/AngleSharpExtensions.cs diff --git a/src/bunit.web/Extensions/Internal/AngleSharpWrapperExtensions.cs b/src/bunit/Extensions/Internal/AngleSharpWrapperExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/Internal/AngleSharpWrapperExtensions.cs rename to src/bunit/Extensions/Internal/AngleSharpWrapperExtensions.cs diff --git a/src/bunit.web/Extensions/Internal/CssSelectorElementFactory.cs b/src/bunit/Extensions/Internal/CssSelectorElementFactory.cs similarity index 100% rename from src/bunit.web/Extensions/Internal/CssSelectorElementFactory.cs rename to src/bunit/Extensions/Internal/CssSelectorElementFactory.cs diff --git a/src/bunit.web/Extensions/Internal/RefreshableElementCollection.cs b/src/bunit/Extensions/Internal/RefreshableElementCollection.cs similarity index 100% rename from src/bunit.web/Extensions/Internal/RefreshableElementCollection.cs rename to src/bunit/Extensions/Internal/RefreshableElementCollection.cs diff --git a/src/bunit.core/Extensions/LoggerHelperExtensions.cs b/src/bunit/Extensions/LoggerHelperExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/LoggerHelperExtensions.cs rename to src/bunit/Extensions/LoggerHelperExtensions.cs diff --git a/src/bunit.web/Extensions/NodePrintExtensions.cs b/src/bunit/Extensions/NodePrintExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/NodePrintExtensions.cs rename to src/bunit/Extensions/NodePrintExtensions.cs diff --git a/src/bunit.core/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/RenderedComponentRenderExtensions.cs rename to src/bunit/Extensions/RenderedComponentRenderExtensions.cs diff --git a/src/bunit.web/Extensions/RenderedFragmentExtensions.cs b/src/bunit/Extensions/RenderedFragmentExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/RenderedFragmentExtensions.cs rename to src/bunit/Extensions/RenderedFragmentExtensions.cs diff --git a/src/bunit.core/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/RenderedFragmentInvokeAsyncExtensions.cs rename to src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs diff --git a/src/bunit.web/Extensions/StubComponentFactoryCollectionExtensions.cs b/src/bunit/Extensions/StubComponentFactoryCollectionExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/StubComponentFactoryCollectionExtensions.cs rename to src/bunit/Extensions/StubComponentFactoryCollectionExtensions.cs diff --git a/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs b/src/bunit/Extensions/TestContextBaseRenderExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs rename to src/bunit/Extensions/TestContextBaseRenderExtensions.cs diff --git a/src/bunit.web/Extensions/TestRendererExtensions.cs b/src/bunit/Extensions/TestRendererExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/TestRendererExtensions.cs rename to src/bunit/Extensions/TestRendererExtensions.cs diff --git a/src/bunit.web/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/TestServiceProviderExtensions.cs similarity index 100% rename from src/bunit.web/Extensions/TestServiceProviderExtensions.cs rename to src/bunit/Extensions/TestServiceProviderExtensions.cs diff --git a/src/bunit.web/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs similarity index 99% rename from src/bunit.web/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs rename to src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs index e9fe9da28..f6fac5d47 100644 --- a/src/bunit.web/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.cs +++ b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs @@ -7,7 +7,7 @@ namespace Bunit; /// /// Helper methods dealing with async rendering during testing. /// -public static class RenderedFragmentWaitForHelperExtensions +public static partial class RenderedFragmentWaitForHelperExtensions { /// /// Wait until an element matching the exists in the , diff --git a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs new file mode 100644 index 000000000..a270ebbbf --- /dev/null +++ b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs @@ -0,0 +1,100 @@ +using System.Runtime.ExceptionServices; +using Bunit.Asserting; +using Bunit.Extensions.WaitForHelpers; + +namespace Bunit; + +/// +/// Helper methods dealing with async rendering during testing. +/// +public static partial class RenderedFragmentWaitForHelperExtensions +{ + /// + /// Wait until the provided action returns true, + /// or the is reached (default is one second). + /// + /// The is evaluated initially, and then each time + /// the renders. + /// + /// The render fragment or component to attempt to verify state against. + /// The predicate to invoke after each render, which must returns true when the desired state has been reached. + /// The maximum time to wait for the desired state. + /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. + /// + /// If a debugger is attached the timeout is set to , giving the possibility to debug without the timeout triggering. + /// + public static void WaitForState(this IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) + { + using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); + + try + { + waiter.WaitTask.GetAwaiter().GetResult(); + } + catch (AggregateException e) when (e.InnerExceptions.Count == 1) + { + ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw(); + } + } + + /// + /// Wait until the provided action returns true, + /// or the is reached (default is one second). + /// + /// The is evaluated initially, and then each time + /// the renders. + /// + /// The render fragment or component to attempt to verify state against. + /// The predicate to invoke after each render, which must returns true when the desired state has been reached. + /// The maximum time to wait for the desired state. + /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. + internal static async Task WaitForStateAsync(this IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) + { + using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); + + await waiter.WaitTask; + } + + /// + /// Wait until the provided passes (i.e. does not throw an + /// exception), or the is reached (default is one second). + /// + /// The is attempted initially, and then each time the renders. + /// + /// The rendered fragment to wait for renders from and assert against. + /// The verification or assertion to perform. + /// The maximum time to attempt the verification. + /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. + [AssertionMethod] + public static void WaitForAssertion(this IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) + { + using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); + + try + { + waiter.WaitTask.GetAwaiter().GetResult(); + } + catch (AggregateException e) when (e.InnerExceptions.Count == 1) + { + ExceptionDispatchInfo.Capture(e.InnerExceptions[0]).Throw(); + } + } + + /// + /// Wait until the provided passes (i.e. does not throw an + /// exception), or the is reached (default is one second). + /// + /// The is attempted initially, and then each time the renders. + /// + /// The rendered fragment to wait for renders from and assert against. + /// The verification or assertion to perform. + /// The maximum time to attempt the verification. + /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. + [AssertionMethod] + internal static async Task WaitForAssertionAsync(this IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) + { + using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); + + await waiter.WaitTask; + } +} diff --git a/src/bunit.core/Extensions/WaitForHelpers/WaitForAssertionHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs similarity index 100% rename from src/bunit.core/Extensions/WaitForHelpers/WaitForAssertionHelper.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs diff --git a/src/bunit.web/Extensions/WaitForHelpers/WaitForElementHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForElementHelper.cs similarity index 100% rename from src/bunit.web/Extensions/WaitForHelpers/WaitForElementHelper.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForElementHelper.cs diff --git a/src/bunit.web/Extensions/WaitForHelpers/WaitForElementsHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForElementsHelper.cs similarity index 100% rename from src/bunit.web/Extensions/WaitForHelpers/WaitForElementsHelper.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForElementsHelper.cs diff --git a/src/bunit.core/Extensions/WaitForHelpers/WaitForFailedException.cs b/src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs similarity index 100% rename from src/bunit.core/Extensions/WaitForHelpers/WaitForFailedException.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForFailedException.cs diff --git a/src/bunit.core/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs similarity index 100% rename from src/bunit.core/Extensions/WaitForHelpers/WaitForHelper.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs diff --git a/src/bunit.core/Extensions/WaitForHelpers/WaitForHelperLoggerExtensions.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelperLoggerExtensions.cs similarity index 100% rename from src/bunit.core/Extensions/WaitForHelpers/WaitForHelperLoggerExtensions.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForHelperLoggerExtensions.cs diff --git a/src/bunit.core/Extensions/WaitForHelpers/WaitForStateHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs similarity index 100% rename from src/bunit.core/Extensions/WaitForHelpers/WaitForStateHelper.cs rename to src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs diff --git a/src/bunit.core/IComponentFactory.cs b/src/bunit/IComponentFactory.cs similarity index 100% rename from src/bunit.core/IComponentFactory.cs rename to src/bunit/IComponentFactory.cs diff --git a/src/bunit.web/IRenderedComponent.cs b/src/bunit/IRenderedComponent.cs similarity index 100% rename from src/bunit.web/IRenderedComponent.cs rename to src/bunit/IRenderedComponent.cs diff --git a/src/bunit.core/IRenderedComponentBase.cs b/src/bunit/IRenderedComponentBase.cs similarity index 100% rename from src/bunit.core/IRenderedComponentBase.cs rename to src/bunit/IRenderedComponentBase.cs diff --git a/src/bunit.web/IRenderedFragment.cs b/src/bunit/IRenderedFragment.cs similarity index 100% rename from src/bunit.web/IRenderedFragment.cs rename to src/bunit/IRenderedFragment.cs diff --git a/src/bunit.core/IRenderedFragmentBase.cs b/src/bunit/IRenderedFragmentBase.cs similarity index 100% rename from src/bunit.core/IRenderedFragmentBase.cs rename to src/bunit/IRenderedFragmentBase.cs diff --git a/src/bunit/InternalsVisibleTo.cs b/src/bunit/InternalsVisibleTo.cs new file mode 100644 index 000000000..a3c9cf4b0 --- /dev/null +++ b/src/bunit/InternalsVisibleTo.cs @@ -0,0 +1 @@ +[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bunit.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010001be6b1a2ca57b09b7040e2ab0993e515296ae22aef4031a4fe388a1336fe21f69c7e8610e9935de6ed18d94b5c98429f99ef62ce3d0af28a7088f856239368ea808ad4c448aa2a8075ed581f989f36ed0d0b8b1cfcaf1ff6a4506c8a99b7024b6eb56996d08e3c9c1cf5db59bff96fcc63ccad155ef7fc63aab6a69862437b6")] diff --git a/src/bunit.web/JSInterop/BunitJSInterop.cs b/src/bunit/JSInterop/BunitJSInterop.cs similarity index 100% rename from src/bunit.web/JSInterop/BunitJSInterop.cs rename to src/bunit/JSInterop/BunitJSInterop.cs diff --git a/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.cs b/src/bunit/JSInterop/BunitJSInteropSetupExtensions.cs similarity index 100% rename from src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.cs rename to src/bunit/JSInterop/BunitJSInteropSetupExtensions.cs diff --git a/src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.net5.cs b/src/bunit/JSInterop/BunitJSInteropSetupExtensions.net5.cs similarity index 100% rename from src/bunit.web/JSInterop/BunitJSInteropSetupExtensions.net5.cs rename to src/bunit/JSInterop/BunitJSInteropSetupExtensions.net5.cs diff --git a/src/bunit.web/JSInterop/BunitJSModuleInterop.cs b/src/bunit/JSInterop/BunitJSModuleInterop.cs similarity index 100% rename from src/bunit.web/JSInterop/BunitJSModuleInterop.cs rename to src/bunit/JSInterop/BunitJSModuleInterop.cs diff --git a/src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs b/src/bunit/JSInterop/Implementation/BunitJSObjectReference.cs similarity index 100% rename from src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs rename to src/bunit/JSInterop/Implementation/BunitJSObjectReference.cs diff --git a/src/bunit.web/JSInterop/Implementation/BunitJSRuntime.cs b/src/bunit/JSInterop/Implementation/BunitJSRuntime.cs similarity index 100% rename from src/bunit.web/JSInterop/Implementation/BunitJSRuntime.cs rename to src/bunit/JSInterop/Implementation/BunitJSRuntime.cs diff --git a/src/bunit.web/JSInterop/Implementation/BunitJSRuntime.net5.cs b/src/bunit/JSInterop/Implementation/BunitJSRuntime.net5.cs similarity index 100% rename from src/bunit.web/JSInterop/Implementation/BunitJSRuntime.net5.cs rename to src/bunit/JSInterop/Implementation/BunitJSRuntime.net5.cs diff --git a/src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs b/src/bunit/JSInterop/Implementation/JSRuntimeExtensions.cs similarity index 100% rename from src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs rename to src/bunit/JSInterop/Implementation/JSRuntimeExtensions.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/FocusAsyncInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/FocusOnNavigateHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/InputFileInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/JSObjectReferenceInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/LooseModeJSObjectReferenceInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/NavigationLockDisableNavigationPromptInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/NavigationLockEnableNavigationPromptInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/Implementation/VirtualizeJSRuntimeInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs b/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs rename to src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs b/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs rename to src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandlerBase{TResult}.cs diff --git a/src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler{TResult}.cs b/src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler{TResult}.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler{TResult}.cs rename to src/bunit/JSInterop/InvocationHandlers/JSRuntimeInvocationHandler{TResult}.cs diff --git a/src/bunit.web/JSInterop/InvocationMatcher.cs b/src/bunit/JSInterop/InvocationMatcher.cs similarity index 100% rename from src/bunit.web/JSInterop/InvocationMatcher.cs rename to src/bunit/JSInterop/InvocationMatcher.cs diff --git a/src/bunit.web/JSInterop/JSRuntimeInvocation.cs b/src/bunit/JSInterop/JSRuntimeInvocation.cs similarity index 100% rename from src/bunit.web/JSInterop/JSRuntimeInvocation.cs rename to src/bunit/JSInterop/JSRuntimeInvocation.cs diff --git a/src/bunit.web/JSInterop/JSRuntimeInvocationDictionary.cs b/src/bunit/JSInterop/JSRuntimeInvocationDictionary.cs similarity index 100% rename from src/bunit.web/JSInterop/JSRuntimeInvocationDictionary.cs rename to src/bunit/JSInterop/JSRuntimeInvocationDictionary.cs diff --git a/src/bunit.web/JSInterop/JSRuntimeMode.cs b/src/bunit/JSInterop/JSRuntimeMode.cs similarity index 100% rename from src/bunit.web/JSInterop/JSRuntimeMode.cs rename to src/bunit/JSInterop/JSRuntimeMode.cs diff --git a/src/bunit.web/JSInterop/JSRuntimeUnhandledInvocationException.cs b/src/bunit/JSInterop/JSRuntimeUnhandledInvocationException.cs similarity index 100% rename from src/bunit.web/JSInterop/JSRuntimeUnhandledInvocationException.cs rename to src/bunit/JSInterop/JSRuntimeUnhandledInvocationException.cs diff --git a/src/bunit.core/ParameterException.cs b/src/bunit/ParameterException.cs similarity index 100% rename from src/bunit.core/ParameterException.cs rename to src/bunit/ParameterException.cs diff --git a/src/bunit.core/Rendering/BunitComponentActivator.cs b/src/bunit/Rendering/BunitComponentActivator.cs similarity index 100% rename from src/bunit.core/Rendering/BunitComponentActivator.cs rename to src/bunit/Rendering/BunitComponentActivator.cs diff --git a/src/bunit.web/Rendering/BunitHtmlParser.cs b/src/bunit/Rendering/BunitHtmlParser.cs similarity index 100% rename from src/bunit.web/Rendering/BunitHtmlParser.cs rename to src/bunit/Rendering/BunitHtmlParser.cs diff --git a/src/bunit.core/Rendering/ComponentDisposedException.cs b/src/bunit/Rendering/ComponentDisposedException.cs similarity index 100% rename from src/bunit.core/Rendering/ComponentDisposedException.cs rename to src/bunit/Rendering/ComponentDisposedException.cs diff --git a/src/bunit.core/Rendering/ComponentNotFoundException.cs b/src/bunit/Rendering/ComponentNotFoundException.cs similarity index 100% rename from src/bunit.core/Rendering/ComponentNotFoundException.cs rename to src/bunit/Rendering/ComponentNotFoundException.cs diff --git a/src/bunit.core/Rendering/FragmentContainer.cs b/src/bunit/Rendering/FragmentContainer.cs similarity index 100% rename from src/bunit.core/Rendering/FragmentContainer.cs rename to src/bunit/Rendering/FragmentContainer.cs diff --git a/src/bunit.core/Rendering/IRenderedComponentActivator.cs b/src/bunit/Rendering/IRenderedComponentActivator.cs similarity index 100% rename from src/bunit.core/Rendering/IRenderedComponentActivator.cs rename to src/bunit/Rendering/IRenderedComponentActivator.cs diff --git a/src/bunit.core/Rendering/ITestRenderer.cs b/src/bunit/Rendering/ITestRenderer.cs similarity index 100% rename from src/bunit.core/Rendering/ITestRenderer.cs rename to src/bunit/Rendering/ITestRenderer.cs diff --git a/src/bunit.web/Rendering/Internal/BunitHtmlParserHelpers.cs b/src/bunit/Rendering/Internal/BunitHtmlParserHelpers.cs similarity index 100% rename from src/bunit.web/Rendering/Internal/BunitHtmlParserHelpers.cs rename to src/bunit/Rendering/Internal/BunitHtmlParserHelpers.cs diff --git a/src/bunit.web/Rendering/Internal/Htmlizer.cs b/src/bunit/Rendering/Internal/Htmlizer.cs similarity index 100% rename from src/bunit.web/Rendering/Internal/Htmlizer.cs rename to src/bunit/Rendering/Internal/Htmlizer.cs diff --git a/src/bunit.core/Rendering/RenderEvent.cs b/src/bunit/Rendering/RenderEvent.cs similarity index 100% rename from src/bunit.core/Rendering/RenderEvent.cs rename to src/bunit/Rendering/RenderEvent.cs diff --git a/src/bunit.core/Rendering/RenderTreeFrameDictionary.cs b/src/bunit/Rendering/RenderTreeFrameDictionary.cs similarity index 100% rename from src/bunit.core/Rendering/RenderTreeFrameDictionary.cs rename to src/bunit/Rendering/RenderTreeFrameDictionary.cs diff --git a/src/bunit.web/Rendering/RenderedComponent.cs b/src/bunit/Rendering/RenderedComponent.cs similarity index 100% rename from src/bunit.web/Rendering/RenderedComponent.cs rename to src/bunit/Rendering/RenderedComponent.cs diff --git a/src/bunit.web/Rendering/RenderedComponentActivator.cs b/src/bunit/Rendering/RenderedComponentActivator.cs similarity index 100% rename from src/bunit.web/Rendering/RenderedComponentActivator.cs rename to src/bunit/Rendering/RenderedComponentActivator.cs diff --git a/src/bunit.web/Rendering/RenderedFragment.cs b/src/bunit/Rendering/RenderedFragment.cs similarity index 100% rename from src/bunit.web/Rendering/RenderedFragment.cs rename to src/bunit/Rendering/RenderedFragment.cs diff --git a/src/bunit.core/Rendering/RootComponent.cs b/src/bunit/Rendering/RootComponent.cs similarity index 100% rename from src/bunit.core/Rendering/RootComponent.cs rename to src/bunit/Rendering/RootComponent.cs diff --git a/src/bunit.core/Rendering/RootRenderTree.cs b/src/bunit/Rendering/RootRenderTree.cs similarity index 100% rename from src/bunit.core/Rendering/RootRenderTree.cs rename to src/bunit/Rendering/RootRenderTree.cs diff --git a/src/bunit.core/Rendering/RootRenderTreeRegistration.cs b/src/bunit/Rendering/RootRenderTreeRegistration.cs similarity index 100% rename from src/bunit.core/Rendering/RootRenderTreeRegistration.cs rename to src/bunit/Rendering/RootRenderTreeRegistration.cs diff --git a/src/bunit.core/Rendering/TestRenderer.cs b/src/bunit/Rendering/TestRenderer.cs similarity index 100% rename from src/bunit.core/Rendering/TestRenderer.cs rename to src/bunit/Rendering/TestRenderer.cs diff --git a/src/bunit.core/Rendering/TestRendererLoggerExtensions.cs b/src/bunit/Rendering/TestRendererLoggerExtensions.cs similarity index 100% rename from src/bunit.core/Rendering/TestRendererLoggerExtensions.cs rename to src/bunit/Rendering/TestRendererLoggerExtensions.cs diff --git a/src/bunit.core/Rendering/UnknownEventHandlerIdException.cs b/src/bunit/Rendering/UnknownEventHandlerIdException.cs similarity index 100% rename from src/bunit.core/Rendering/UnknownEventHandlerIdException.cs rename to src/bunit/Rendering/UnknownEventHandlerIdException.cs diff --git a/src/bunit.web/Rendering/WebTestRenderer.cs b/src/bunit/Rendering/WebTestRenderer.cs similarity index 100% rename from src/bunit.web/Rendering/WebTestRenderer.cs rename to src/bunit/Rendering/WebTestRenderer.cs diff --git a/src/bunit.web/TestContext.cs b/src/bunit/TestContext.cs similarity index 100% rename from src/bunit.web/TestContext.cs rename to src/bunit/TestContext.cs diff --git a/src/bunit.core/TestContextBase.cs b/src/bunit/TestContextBase.cs similarity index 100% rename from src/bunit.core/TestContextBase.cs rename to src/bunit/TestContextBase.cs diff --git a/src/bunit.web/TestContextWrapper.cs b/src/bunit/TestContextWrapper.cs similarity index 100% rename from src/bunit.web/TestContextWrapper.cs rename to src/bunit/TestContextWrapper.cs diff --git a/src/bunit.web/TestDoubles/Authorization/AuthorizationState.cs b/src/bunit/TestDoubles/Authorization/AuthorizationState.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/AuthorizationState.cs rename to src/bunit/TestDoubles/Authorization/AuthorizationState.cs diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs b/src/bunit/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs rename to src/bunit/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/FakeAuthorizationExtensions.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/FakeAuthorizationExtensions.cs rename to src/bunit/TestDoubles/Authorization/FakeAuthorizationExtensions.cs diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs b/src/bunit/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs rename to src/bunit/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs diff --git a/src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs b/src/bunit/TestDoubles/Authorization/FakeAuthorizationService.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/FakeAuthorizationService.cs rename to src/bunit/TestDoubles/Authorization/FakeAuthorizationService.cs diff --git a/src/bunit.web/TestDoubles/Authorization/MissingFakeAuthorizationException.cs b/src/bunit/TestDoubles/Authorization/MissingFakeAuthorizationException.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/MissingFakeAuthorizationException.cs rename to src/bunit/TestDoubles/Authorization/MissingFakeAuthorizationException.cs diff --git a/src/bunit.web/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs b/src/bunit/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs rename to src/bunit/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs diff --git a/src/bunit.web/TestDoubles/Authorization/PlaceholderAuthorizationService.cs b/src/bunit/TestDoubles/Authorization/PlaceholderAuthorizationService.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/PlaceholderAuthorizationService.cs rename to src/bunit/TestDoubles/Authorization/PlaceholderAuthorizationService.cs diff --git a/src/bunit.web/TestDoubles/Authorization/TestAuthorizationContext.cs b/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/TestAuthorizationContext.cs rename to src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs diff --git a/src/bunit.web/TestDoubles/Authorization/TestPolicyRequirement.cs b/src/bunit/TestDoubles/Authorization/TestPolicyRequirement.cs similarity index 100% rename from src/bunit.web/TestDoubles/Authorization/TestPolicyRequirement.cs rename to src/bunit/TestDoubles/Authorization/TestPolicyRequirement.cs diff --git a/src/bunit.web/TestDoubles/Components/CapturedParameterView{TComponent}.cs b/src/bunit/TestDoubles/Components/CapturedParameterView{TComponent}.cs similarity index 100% rename from src/bunit.web/TestDoubles/Components/CapturedParameterView{TComponent}.cs rename to src/bunit/TestDoubles/Components/CapturedParameterView{TComponent}.cs diff --git a/src/bunit.web/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs b/src/bunit/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs similarity index 100% rename from src/bunit.web/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs rename to src/bunit/TestDoubles/Components/ComponentDoubleBase{TComponent}.cs diff --git a/src/bunit.web/TestDoubles/Components/ParameterNotFoundException.cs b/src/bunit/TestDoubles/Components/ParameterNotFoundException.cs similarity index 100% rename from src/bunit.web/TestDoubles/Components/ParameterNotFoundException.cs rename to src/bunit/TestDoubles/Components/ParameterNotFoundException.cs diff --git a/src/bunit.web/TestDoubles/Components/Stub{TComponent}.cs b/src/bunit/TestDoubles/Components/Stub{TComponent}.cs similarity index 100% rename from src/bunit.web/TestDoubles/Components/Stub{TComponent}.cs rename to src/bunit/TestDoubles/Components/Stub{TComponent}.cs diff --git a/src/bunit.web/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs b/src/bunit/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs similarity index 100% rename from src/bunit.web/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs rename to src/bunit/TestDoubles/ErrorBoundary/BunitErrorBoundaryLogger.cs diff --git a/src/bunit.web/TestDoubles/HttpClient/MissingMockHttpClientException.cs b/src/bunit/TestDoubles/HttpClient/MissingMockHttpClientException.cs similarity index 100% rename from src/bunit.web/TestDoubles/HttpClient/MissingMockHttpClientException.cs rename to src/bunit/TestDoubles/HttpClient/MissingMockHttpClientException.cs diff --git a/src/bunit.web/TestDoubles/HttpClient/PlaceholderHttpClient.cs b/src/bunit/TestDoubles/HttpClient/PlaceholderHttpClient.cs similarity index 100% rename from src/bunit.web/TestDoubles/HttpClient/PlaceholderHttpClient.cs rename to src/bunit/TestDoubles/HttpClient/PlaceholderHttpClient.cs diff --git a/src/bunit.web/TestDoubles/Localization/MissingMockStringLocalizationException.cs b/src/bunit/TestDoubles/Localization/MissingMockStringLocalizationException.cs similarity index 100% rename from src/bunit.web/TestDoubles/Localization/MissingMockStringLocalizationException.cs rename to src/bunit/TestDoubles/Localization/MissingMockStringLocalizationException.cs diff --git a/src/bunit.web/TestDoubles/Localization/PlaceholderStringLocalization.cs b/src/bunit/TestDoubles/Localization/PlaceholderStringLocalization.cs similarity index 100% rename from src/bunit.web/TestDoubles/Localization/PlaceholderStringLocalization.cs rename to src/bunit/TestDoubles/Localization/PlaceholderStringLocalization.cs diff --git a/src/bunit.web/TestDoubles/NavigationInterception/FakeNavigationInterception.cs b/src/bunit/TestDoubles/NavigationInterception/FakeNavigationInterception.cs similarity index 100% rename from src/bunit.web/TestDoubles/NavigationInterception/FakeNavigationInterception.cs rename to src/bunit/TestDoubles/NavigationInterception/FakeNavigationInterception.cs diff --git a/src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs b/src/bunit/TestDoubles/NavigationManager/FakeNavigationManager.cs similarity index 100% rename from src/bunit.web/TestDoubles/NavigationManager/FakeNavigationManager.cs rename to src/bunit/TestDoubles/NavigationManager/FakeNavigationManager.cs diff --git a/src/bunit.web/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs b/src/bunit/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs similarity index 100% rename from src/bunit.web/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs rename to src/bunit/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs diff --git a/src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs b/src/bunit/TestDoubles/NavigationManager/NavigationHistory.cs similarity index 100% rename from src/bunit.web/TestDoubles/NavigationManager/NavigationHistory.cs rename to src/bunit/TestDoubles/NavigationManager/NavigationHistory.cs diff --git a/src/bunit.web/TestDoubles/NavigationManager/NavigationState.cs b/src/bunit/TestDoubles/NavigationManager/NavigationState.cs similarity index 100% rename from src/bunit.web/TestDoubles/NavigationManager/NavigationState.cs rename to src/bunit/TestDoubles/NavigationManager/NavigationState.cs diff --git a/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs similarity index 100% rename from src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs rename to src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs diff --git a/src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs b/src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs similarity index 100% rename from src/bunit.core/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs rename to src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs diff --git a/src/bunit.core/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs b/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs similarity index 100% rename from src/bunit.core/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs rename to src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs diff --git a/src/bunit.web/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs b/src/bunit/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs similarity index 100% rename from src/bunit.web/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs rename to src/bunit/TestDoubles/ScrollToLocationHash/BunitScrollToLocationHash.cs diff --git a/src/bunit.web/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs b/src/bunit/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs similarity index 100% rename from src/bunit.web/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs rename to src/bunit/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs diff --git a/src/bunit.core/TestServiceProvider.cs b/src/bunit/TestServiceProvider.cs similarity index 100% rename from src/bunit.core/TestServiceProvider.cs rename to src/bunit/TestServiceProvider.cs diff --git a/src/bunit/bunit.csproj b/src/bunit/bunit.csproj index 991e3c475..4e0dc3cff 100644 --- a/src/bunit/bunit.csproj +++ b/src/bunit/bunit.csproj @@ -1,9 +1,6 @@ net8.0;net9.0 - true - false - false @@ -21,8 +18,33 @@ - - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/src.sln b/src/src.sln deleted file mode 100644 index 47e5b30dc..000000000 --- a/src/src.sln +++ /dev/null @@ -1,60 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.5.002.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit", "bunit\bunit.csproj", "{91DF582A-7C2B-4437-AB28-EE9FBED907A0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.core", "bunit.core\bunit.core.csproj", "{EC350F53-49A3-498A-B349-59BC6C0EB236}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.template", "bunit.template\bunit.template.csproj", "{1E035DBC-EFCF-4A4B-86A3-A4AA0E3A1EEE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.web", "bunit.web\bunit.web.csproj", "{73994570-A89F-4726-8A6F-DFA53947DD29}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "bunit.web.query", "bunit.web.query\bunit.web.query.csproj", "{F3C4F8A2-1B48-4E70-B66B-E14E97C38927}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "bunit.template (1)", "bunit.template (1)", "{C7995CF2-FFAB-4409-8AFB-74698442B784}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Company.BlazorTests1", "bunit.template\template\Company.BlazorTests1.csproj", "{537418EE-DC2C-4611-B16A-B986D41740EE}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {91DF582A-7C2B-4437-AB28-EE9FBED907A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {91DF582A-7C2B-4437-AB28-EE9FBED907A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {91DF582A-7C2B-4437-AB28-EE9FBED907A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {91DF582A-7C2B-4437-AB28-EE9FBED907A0}.Release|Any CPU.Build.0 = Release|Any CPU - {EC350F53-49A3-498A-B349-59BC6C0EB236}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EC350F53-49A3-498A-B349-59BC6C0EB236}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EC350F53-49A3-498A-B349-59BC6C0EB236}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EC350F53-49A3-498A-B349-59BC6C0EB236}.Release|Any CPU.Build.0 = Release|Any CPU - {1E035DBC-EFCF-4A4B-86A3-A4AA0E3A1EEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1E035DBC-EFCF-4A4B-86A3-A4AA0E3A1EEE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1E035DBC-EFCF-4A4B-86A3-A4AA0E3A1EEE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1E035DBC-EFCF-4A4B-86A3-A4AA0E3A1EEE}.Release|Any CPU.Build.0 = Release|Any CPU - {73994570-A89F-4726-8A6F-DFA53947DD29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {73994570-A89F-4726-8A6F-DFA53947DD29}.Debug|Any CPU.Build.0 = Debug|Any CPU - {73994570-A89F-4726-8A6F-DFA53947DD29}.Release|Any CPU.ActiveCfg = Release|Any CPU - {73994570-A89F-4726-8A6F-DFA53947DD29}.Release|Any CPU.Build.0 = Release|Any CPU - {F3C4F8A2-1B48-4E70-B66B-E14E97C38927}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F3C4F8A2-1B48-4E70-B66B-E14E97C38927}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F3C4F8A2-1B48-4E70-B66B-E14E97C38927}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F3C4F8A2-1B48-4E70-B66B-E14E97C38927}.Release|Any CPU.Build.0 = Release|Any CPU - {537418EE-DC2C-4611-B16A-B986D41740EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {537418EE-DC2C-4611-B16A-B986D41740EE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {537418EE-DC2C-4611-B16A-B986D41740EE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {537418EE-DC2C-4611-B16A-B986D41740EE}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {537418EE-DC2C-4611-B16A-B986D41740EE} = {C7995CF2-FFAB-4409-8AFB-74698442B784} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {28522EFE-F7F9-42C1-9A91-EC9D8EC08CDB} - EndGlobalSection -EndGlobal diff --git a/tests/bunit.generators.tests/bunit.generators.tests.csproj b/tests/bunit.generators.tests/bunit.generators.tests.csproj index 236bac0a1..ed73823e2 100644 --- a/tests/bunit.generators.tests/bunit.generators.tests.csproj +++ b/tests/bunit.generators.tests/bunit.generators.tests.csproj @@ -34,7 +34,7 @@ - + diff --git a/tests/bunit.web.tests/Assembly.cs b/tests/bunit.tests/Assembly.cs similarity index 100% rename from tests/bunit.web.tests/Assembly.cs rename to tests/bunit.tests/Assembly.cs diff --git a/tests/bunit.web.tests/Asserting/CompareToDiffingExtensionsTest.cs b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/Asserting/CompareToDiffingExtensionsTest.cs rename to tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs diff --git a/tests/bunit.web.tests/Asserting/JSRuntimeAssertExtensionsTest.cs b/tests/bunit.tests/Asserting/JSRuntimeAssertExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/Asserting/JSRuntimeAssertExtensionsTest.cs rename to tests/bunit.tests/Asserting/JSRuntimeAssertExtensionsTest.cs diff --git a/tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs rename to tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs diff --git a/tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs similarity index 100% rename from tests/bunit.web.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs rename to tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs diff --git a/tests/bunit.web.tests/Asserting/MarkupMatchesTests.razor b/tests/bunit.tests/Asserting/MarkupMatchesTests.razor similarity index 100% rename from tests/bunit.web.tests/Asserting/MarkupMatchesTests.razor rename to tests/bunit.tests/Asserting/MarkupMatchesTests.razor diff --git a/tests/bunit.web.tests/BlazorE2E/ComponentRenderingTest.cs b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs similarity index 100% rename from tests/bunit.web.tests/BlazorE2E/ComponentRenderingTest.cs rename to tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs diff --git a/tests/bunit.core.tests/ComponentFactories/ConditionalComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs similarity index 100% rename from tests/bunit.core.tests/ComponentFactories/ConditionalComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs diff --git a/tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs similarity index 100% rename from tests/bunit.core.tests/ComponentFactories/GenericComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs diff --git a/tests/bunit.core.tests/ComponentFactories/InstanceComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs similarity index 100% rename from tests/bunit.core.tests/ComponentFactories/InstanceComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs diff --git a/tests/bunit.web.tests/ComponentFactories/StubComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs similarity index 100% rename from tests/bunit.web.tests/ComponentFactories/StubComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs diff --git a/tests/bunit.core.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs similarity index 100% rename from tests/bunit.core.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs diff --git a/tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs similarity index 100% rename from tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.cs rename to tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs diff --git a/tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.razor b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor similarity index 100% rename from tests/bunit.core.tests/ComponentParameterCollectionBuilderTests.razor rename to tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor diff --git a/tests/bunit.core.tests/ComponentParameterCollectionTest.cs b/tests/bunit.tests/ComponentParameterCollectionTest.cs similarity index 100% rename from tests/bunit.core.tests/ComponentParameterCollectionTest.cs rename to tests/bunit.tests/ComponentParameterCollectionTest.cs diff --git a/tests/bunit.core.tests/ComponentParameterFactoryTest.cs b/tests/bunit.tests/ComponentParameterFactoryTest.cs similarity index 100% rename from tests/bunit.core.tests/ComponentParameterFactoryTest.cs rename to tests/bunit.tests/ComponentParameterFactoryTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/KeyTest.cs b/tests/bunit.tests/EventDispatchExtensions/KeyTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/KeyTest.cs rename to tests/bunit.tests/EventDispatchExtensions/KeyTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/TriggerEventSpy.cs b/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/TriggerEventSpy.cs rename to tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs diff --git a/tests/bunit.web.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs diff --git a/tests/bunit.web.tests/Extensions/InputFile/InputFileTests.cs b/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs similarity index 100% rename from tests/bunit.web.tests/Extensions/InputFile/InputFileTests.cs rename to tests/bunit.tests/Extensions/InputFile/InputFileTests.cs diff --git a/tests/bunit.web.tests/Extensions/RefreshableQueryCollectionTest.cs b/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs similarity index 100% rename from tests/bunit.web.tests/Extensions/RefreshableQueryCollectionTest.cs rename to tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs diff --git a/tests/bunit.web.tests/Extensions/RefreshingWrappedElementTest.cs b/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs similarity index 100% rename from tests/bunit.web.tests/Extensions/RefreshingWrappedElementTest.cs rename to tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs diff --git a/tests/bunit.core.tests/Extensions/RenderedComponentRenderExtensionsTest.cs b/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs similarity index 100% rename from tests/bunit.core.tests/Extensions/RenderedComponentRenderExtensionsTest.cs rename to tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs diff --git a/tests/bunit.web.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs similarity index 100% rename from tests/bunit.web.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs rename to tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs diff --git a/tests/bunit.web.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs similarity index 100% rename from tests/bunit.web.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs rename to tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs diff --git a/tests/bunit.core.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs similarity index 100% rename from tests/bunit.core.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs rename to tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs diff --git a/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/BunitJSInteropTest.cs rename to tests/bunit.tests/JSInterop/BunitJSInteropTest.cs diff --git a/tests/bunit.web.tests/JSInterop/BunitJSInteropTest.net5.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTest.net5.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/BunitJSInteropTest.net5.cs rename to tests/bunit.tests/JSInterop/BunitJSInteropTest.net5.cs diff --git a/tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs b/tests/bunit.tests/JSInterop/BunitJSObjectReferenceTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/BunitJSObjectReferenceTest.cs rename to tests/bunit.tests/JSInterop/BunitJSObjectReferenceTest.cs diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs rename to tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs rename to tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs diff --git a/tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs rename to tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs diff --git a/tests/bunit.web.tests/JSInterop/JSRuntimeInvocationTest.cs b/tests/bunit.tests/JSInterop/JSRuntimeInvocationTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/JSRuntimeInvocationTest.cs rename to tests/bunit.tests/JSInterop/JSRuntimeInvocationTest.cs diff --git a/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs rename to tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs diff --git a/tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs similarity index 100% rename from tests/bunit.web.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs rename to tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs diff --git a/tests/bunit.core.tests/Rendering/BunitComponentActivatorTest.cs b/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs similarity index 100% rename from tests/bunit.core.tests/Rendering/BunitComponentActivatorTest.cs rename to tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs diff --git a/tests/bunit.web.tests/Rendering/BunitHtmlParserTest.cs b/tests/bunit.tests/Rendering/BunitHtmlParserTest.cs similarity index 100% rename from tests/bunit.web.tests/Rendering/BunitHtmlParserTest.cs rename to tests/bunit.tests/Rendering/BunitHtmlParserTest.cs diff --git a/tests/bunit.core.tests/Rendering/ComponentParameterTest.cs b/tests/bunit.tests/Rendering/ComponentParameterTest.cs similarity index 100% rename from tests/bunit.core.tests/Rendering/ComponentParameterTest.cs rename to tests/bunit.tests/Rendering/ComponentParameterTest.cs diff --git a/tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.cs b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs similarity index 100% rename from tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.cs rename to tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs diff --git a/tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.net5.cs similarity index 100% rename from tests/bunit.web.tests/Rendering/Internal/HtmlizerTests.net5.cs rename to tests/bunit.tests/Rendering/Internal/HtmlizerTests.net5.cs diff --git a/tests/bunit.web.tests/Rendering/RenderedComponentTest.cs b/tests/bunit.tests/Rendering/RenderedComponentTest.cs similarity index 100% rename from tests/bunit.web.tests/Rendering/RenderedComponentTest.cs rename to tests/bunit.tests/Rendering/RenderedComponentTest.cs diff --git a/tests/bunit.web.tests/Rendering/RenderedFragmentTest.cs b/tests/bunit.tests/Rendering/RenderedFragmentTest.cs similarity index 100% rename from tests/bunit.web.tests/Rendering/RenderedFragmentTest.cs rename to tests/bunit.tests/Rendering/RenderedFragmentTest.cs diff --git a/tests/bunit.core.tests/Rendering/RootRenderTreeTest.cs b/tests/bunit.tests/Rendering/RootRenderTreeTest.cs similarity index 100% rename from tests/bunit.core.tests/Rendering/RootRenderTreeTest.cs rename to tests/bunit.tests/Rendering/RootRenderTreeTest.cs diff --git a/tests/bunit.core.tests/Rendering/TestRendererTest.cs b/tests/bunit.tests/Rendering/TestRendererTest.cs similarity index 100% rename from tests/bunit.core.tests/Rendering/TestRendererTest.cs rename to tests/bunit.tests/Rendering/TestRendererTest.cs diff --git a/tests/bunit.core.tests/Rendering/TestRendererTest.net5.cs b/tests/bunit.tests/Rendering/TestRendererTest.net5.cs similarity index 100% rename from tests/bunit.core.tests/Rendering/TestRendererTest.net5.cs rename to tests/bunit.tests/Rendering/TestRendererTest.net5.cs diff --git a/tests/bunit.core.tests/ShouldlyExtensions.cs b/tests/bunit.tests/ShouldlyExtensions.cs similarity index 100% rename from tests/bunit.core.tests/ShouldlyExtensions.cs rename to tests/bunit.tests/ShouldlyExtensions.cs diff --git a/tests/bunit.core.tests/TestContextBaseTest.cs b/tests/bunit.tests/TestContextBaseTest.cs similarity index 100% rename from tests/bunit.core.tests/TestContextBaseTest.cs rename to tests/bunit.tests/TestContextBaseTest.cs diff --git a/tests/bunit.core.tests/TestContextBaseTest.net5.cs b/tests/bunit.tests/TestContextBaseTest.net5.cs similarity index 100% rename from tests/bunit.core.tests/TestContextBaseTest.net5.cs rename to tests/bunit.tests/TestContextBaseTest.net5.cs diff --git a/tests/bunit.web.tests/TestContextTest.cs b/tests/bunit.tests/TestContextTest.cs similarity index 100% rename from tests/bunit.web.tests/TestContextTest.cs rename to tests/bunit.tests/TestContextTest.cs diff --git a/tests/bunit.web.tests/TestContextTest.net6.cs b/tests/bunit.tests/TestContextTest.net6.cs similarity index 100% rename from tests/bunit.web.tests/TestContextTest.net6.cs rename to tests/bunit.tests/TestContextTest.net6.cs diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Authorization/AuthorizationTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs b/tests/bunit.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs b/tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs b/tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs b/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Components/CapturedParameterViewTest.cs b/tests/bunit.tests/TestDoubles/Components/CapturedParameterViewTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Components/CapturedParameterViewTest.cs rename to tests/bunit.tests/TestDoubles/Components/CapturedParameterViewTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs rename to tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/Components/StubTest.cs b/tests/bunit.tests/TestDoubles/Components/StubTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/Components/StubTest.cs rename to tests/bunit.tests/TestDoubles/Components/StubTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs b/tests/bunit.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs rename to tests/bunit.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs b/tests/bunit.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs rename to tests/bunit.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs rename to tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs diff --git a/tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs similarity index 100% rename from tests/bunit.web.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs rename to tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs diff --git a/tests/bunit.core.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs b/tests/bunit.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs similarity index 100% rename from tests/bunit.core.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs rename to tests/bunit.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs diff --git a/tests/bunit.core.tests/TestServiceProviderTest.cs b/tests/bunit.tests/TestServiceProviderTest.cs similarity index 100% rename from tests/bunit.core.tests/TestServiceProviderTest.cs rename to tests/bunit.tests/TestServiceProviderTest.cs diff --git a/tests/bunit.web.tests/TestUtilities/JSRuntimeInvocationAssertionHelpers.cs b/tests/bunit.tests/TestUtilities/JSRuntimeInvocationAssertionHelpers.cs similarity index 100% rename from tests/bunit.web.tests/TestUtilities/JSRuntimeInvocationAssertionHelpers.cs rename to tests/bunit.tests/TestUtilities/JSRuntimeInvocationAssertionHelpers.cs diff --git a/tests/bunit.web.tests/TestUtilities/MockingHelpers.cs b/tests/bunit.tests/TestUtilities/MockingHelpers.cs similarity index 100% rename from tests/bunit.web.tests/TestUtilities/MockingHelpers.cs rename to tests/bunit.tests/TestUtilities/MockingHelpers.cs diff --git a/tests/bunit.core.tests/_Imports.razor b/tests/bunit.tests/_Imports.razor similarity index 100% rename from tests/bunit.core.tests/_Imports.razor rename to tests/bunit.tests/_Imports.razor diff --git a/tests/bunit.core.tests/bunit.core.tests.csproj b/tests/bunit.tests/bunit.tests.csproj similarity index 78% rename from tests/bunit.core.tests/bunit.core.tests.csproj rename to tests/bunit.tests/bunit.tests.csproj index fcdc324e8..bba7bc855 100644 --- a/tests/bunit.core.tests/bunit.core.tests.csproj +++ b/tests/bunit.tests/bunit.tests.csproj @@ -3,12 +3,11 @@ net8.0;net9.0 Bunit - Bunit.Core.Tests + Bunit.Tests - - + diff --git a/tests/bunit.core.tests/xunit.runner.json b/tests/bunit.tests/xunit.runner.json similarity index 100% rename from tests/bunit.core.tests/xunit.runner.json rename to tests/bunit.tests/xunit.runner.json 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 b3b2dfa52..ee8a7d400 100644 --- a/tests/bunit.web.query.tests/bunit.web.query.tests.csproj +++ b/tests/bunit.web.query.tests/bunit.web.query.tests.csproj @@ -7,8 +7,7 @@ - - + diff --git a/tests/bunit.web.tests/bunit.web.tests.csproj b/tests/bunit.web.tests/bunit.web.tests.csproj deleted file mode 100644 index 2d486a751..000000000 --- a/tests/bunit.web.tests/bunit.web.tests.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - net8.0;net9.0 - Bunit - Bunit.Web.Tests - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers - NU1701 - - - - \ No newline at end of file diff --git a/tests/bunit.web.tests/xunit.runner.json b/tests/bunit.web.tests/xunit.runner.json deleted file mode 100644 index e37151e81..000000000 --- a/tests/bunit.web.tests/xunit.runner.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", - "diagnosticMessages": false -} From 8a2396e7403b1005a7995971e5baf1c0e13b5c27 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 7 May 2023 22:27:25 +0200 Subject: [PATCH 007/100] feat: Remove unused abstraction --- MIGRATION.md | 8 ++++ .../docs/interaction/awaiting-async-state.md | 4 +- .../docs/interaction/dispose-components.md | 2 +- docs/site/docs/interaction/trigger-renders.md | 16 ++++---- .../site/docs/verification/async-assertion.md | 4 +- .../verification/verify-component-state.md | 8 ++-- src/bunit/Asserting/CompareToExtensions.cs | 6 +-- .../MarkupMatchesAssertExtensions.cs | 4 +- ...actory{TComponent,TSubstituteComponent}.cs | 4 +- .../ComponentFactoryCollectionExtensions.cs | 2 +- .../IRefreshableElementCollection.cs | 4 +- .../RenderedComponentRenderExtensions.cs | 10 ++--- .../Extensions/RenderedFragmentExtensions.cs | 2 +- .../RenderedFragmentInvokeAsyncExtensions.cs | 10 ++--- .../TestContextBaseRenderExtensions.cs | 8 ++-- .../TestServiceProviderExtensions.cs | 2 +- ...entWaitForHelperExtensions.WaitForState.cs | 8 ++-- .../WaitForHelpers/WaitForAssertionHelper.cs | 2 +- .../WaitForHelpers/WaitForHelper.cs | 6 +-- .../WaitForHelpers/WaitForStateHelper.cs | 2 +- src/bunit/IRenderedComponent.cs | 6 ++- src/bunit/IRenderedComponentBase.cs | 14 ------- src/bunit/IRenderedFragment.cs | 36 +++++++++++++++-- src/bunit/IRenderedFragmentBase.cs | 40 ------------------- .../Rendering/ComponentDisposedException.cs | 2 +- .../Rendering/IRenderedComponentActivator.cs | 14 +++---- src/bunit/Rendering/ITestRenderer.cs | 12 +++--- src/bunit/Rendering/RenderEvent.cs | 2 +- .../Rendering/RenderedComponentActivator.cs | 6 +-- src/bunit/Rendering/RenderedFragment.cs | 2 +- src/bunit/Rendering/TestRenderer.cs | 28 +++++++------ src/bunit/Rendering/WebTestRenderer.cs | 28 ------------- src/bunit/TestContext.cs | 8 ++-- src/bunit/TestContextBase.cs | 2 +- ...omponentParameterCollectionBuilderTests.cs | 4 +- .../ComponentParameterCollectionTest.cs | 2 +- .../ComponentParameterFactoryTest.cs | 2 +- .../bunit.tests/Rendering/TestRendererTest.cs | 20 +++++----- 38 files changed, 151 insertions(+), 189 deletions(-) delete mode 100644 src/bunit/IRenderedComponentBase.cs delete mode 100644 src/bunit/IRenderedFragmentBase.cs delete mode 100644 src/bunit/Rendering/WebTestRenderer.cs diff --git a/MIGRATION.md b/MIGRATION.md index 142d55daa..fa9dd9e0d 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -25,3 +25,11 @@ public static class Extensions ## Merge of `bunit.core` and `bunit.web` The `bunit.core` and `bunit.web` packages have been merged into a single `bunit` package. If you used either of these packages, you should remove them and install the `bunit` package instead. + +## Removal of unneeded abstraction + +### `IRenderedComponentBase` and `IRenderedFragmentBase` +`IRenderedComponentBase` and `IRenderedFragmentBase` have been removed. They were used to provide a common base class for `IRenderedComponent` and `IRenderedFragment`, but this is no longer needed (due to the merge of the project). If you used either of these interfaces, you should replace them with `IRenderedComponent` and `IRenderedFragment` respectively. + +### `WebTestRender` merged into `TestRender` +The `WebTestRender` class has been merged into the `TestRender` class. If you used `WebTestRender`, you should replace it with `TestRender`. diff --git a/docs/site/docs/interaction/awaiting-async-state.md b/docs/site/docs/interaction/awaiting-async-state.md index d852df40f..2d7c668af 100644 --- a/docs/site/docs/interaction/awaiting-async-state.md +++ b/docs/site/docs/interaction/awaiting-async-state.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragmentBase,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragmentBase,System.Action,System.Nullable{System.TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) method covered on the page. Let's start by taking a look at the `WaitForState` method in more detail. ## Waiting for state using `WaitForState` -The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragmentBase,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) +The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) > [!NOTE] > The `WaitForState()` method will try the predicate passed to it when the `WaitForState()` method is called, and every time the component under test renders. diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index b0517603d..8995d9e94 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -13,7 +13,7 @@ The following example of this: [!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] > [!WARNING] -> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragmentBase,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragmentBase,System.Action,System.Nullable{System.TimeSpan})) will not work as a disposed component will not trigger a new render cycle. +> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Checking for exceptions `Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.TestContextBase.DisposeComponents) will throw the exception to the user code: diff --git a/docs/site/docs/interaction/trigger-renders.md b/docs/site/docs/interaction/trigger-renders.md index da2b35253..ed60a9e67 100644 --- a/docs/site/docs/interaction/trigger-renders.md +++ b/docs/site/docs/interaction/trigger-renders.md @@ -11,31 +11,31 @@ In `.razor` based tests, using the 's or a in a test, but need a child component's , then use the `FindComponent()` or the `FindComponents()` methods, which traverse down the render tree and finds rendered components. -With a , it is possible to cause the component to render again directly through the [`Render()`](xref:Bunit.TestContext.Render``1(Microsoft.AspNetCore.Components.RenderFragment)) method or one of the [`SetParametersAndRender()`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponentBase{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods, or indirectly through the [`InvokeAsync()`](xref:Bunit.IRenderedFragmentBase.Bunit.RenderedFragmentInvokeAsyncExtensions.InvokeAsync(System.Action)) method. +With a , it is possible to cause the component to render again directly through the [`Render()`](xref:Bunit.TestContext.Render``1(Microsoft.AspNetCore.Components.RenderFragment)) method or one of the [`SetParametersAndRender()`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods, or indirectly through the [`InvokeAsync()`](xref:Bunit.IRenderedFragment.Bunit.RenderedFragmentInvokeAsyncExtensions.InvokeAsync(System.Action)) method. Let's look at how to use each of these methods to cause a re-render. ## Render -The [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.IRenderedComponentBase{``0})) method tells the renderer to re-render the component, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods). To use it, do the following: +The [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.IRenderedComponent{``0})) method tells the renderer to re-render the component, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods). To use it, do the following: [!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=16&end=22&highlight=5)] -The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.IRenderedComponentBase{``0})). +The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.IRenderedComponent{``0})). > [!TIP] -> The number of renders a component has been through can be inspected and verified using the property. +> The number of renders a component has been through can be inspected and verified using the property. ## SetParametersAndRender -The [`SetParametersAndRender(...)`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponentBase{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods tells the renderer to re-render the component with new parameters, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods), passing the new parameters — _but only the new parameters_ — to the `SetParametersAsync()` method. To use it, do the following: +The [`SetParametersAndRender(...)`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods tells the renderer to re-render the component with new parameters, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods), passing the new parameters — _but only the new parameters_ — to the `SetParametersAsync()` method. To use it, do the following: [!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=29&end=39&highlight=7-9)] -The highlighted line shows the call to [`SetParametersAndRender()`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponentBase{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})), which is also available as a version that takes the zero or more component parameters, e.g. created through the component parameter factory helper methods, if you prefer that method of passing parameters. +The highlighted line shows the call to [`SetParametersAndRender()`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})), which is also available as a version that takes the zero or more component parameters, e.g. created through the component parameter factory helper methods, if you prefer that method of passing parameters. > [!NOTE] -> Passing parameters to components through the [`SetParametersAndRender(...)`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponentBase{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods is identical to doing it with the `RenderComponent(...)` methods, described in detail on the page. +> Passing parameters to components through the [`SetParametersAndRender(...)`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods is identical to doing it with the `RenderComponent(...)` methods, described in detail on the page. ## InvokeAsync @@ -72,4 +72,4 @@ This can also be used to assert intermediate states during an asynchronous opera [!code-cshtml[CalcWithLoading.razor](../../../samples/components/CalcWithLoading.razor)] -[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=71&end=82&highlight=7)] \ No newline at end of file +[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=71&end=82&highlight=7)] diff --git a/docs/site/docs/verification/async-assertion.md b/docs/site/docs/verification/async-assertion.md index 3a4f45a4f..4f37ef4a2 100644 --- a/docs/site/docs/verification/async-assertion.md +++ b/docs/site/docs/verification/async-assertion.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass, and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragmentBase,System.Action,System.Nullable{System.TimeSpan})) method covered on this page, and the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragmentBase,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method covered on the page. Let's start by taking a look at the ` WaitForAssertion` method in more detail. ## Waiting for assertion to pass using `WaitForAssertion` -The [`WaitForAssertion(Action, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragmentBase,System.Action,System.Nullable{System.TimeSpan})) method can be used to block and wait in a test method until the provided assert action does not throw an exception, or until the timeout is reached (the default timeout is one second). +The [`WaitForAssertion(Action, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) method can be used to block and wait in a test method until the provided assert action does not throw an exception, or until the timeout is reached (the default timeout is one second). > [!NOTE] > The `WaitForAssertion()` method will try the assert action passed to it when the `WaitForAssertion()` method is called and every time the component under test renders. diff --git a/docs/site/docs/verification/verify-component-state.md b/docs/site/docs/verification/verify-component-state.md index e2f4f6c13..8eb9a2c9d 100644 --- a/docs/site/docs/verification/verify-component-state.md +++ b/docs/site/docs/verification/verify-component-state.md @@ -5,7 +5,7 @@ title: Verifying the state of a component under test # Verifying the state of a component -The instance of a component under test is available through the property on the type. When using the 's `RenderComponent()` method, this is the type returned. +The instance of a component under test is available through the property on the type. When using the 's `RenderComponent()` method, this is the type returned. In `.razor` based tests, using the 's method also returns an (as opposed to the method which returns the more simple ). @@ -14,7 +14,7 @@ In `.razor` based tests, using the 's property on the type provides access to the component under test. For example: +The property on the type provides access to the component under test. For example: ```csharp IRenderedComponent cut = RenderComponent(); @@ -25,9 +25,9 @@ Alert alert = cut.Instance; ``` > [!WARNING] -> While it is possible to set `[Parameter]` and `[CascadingParameter]` properties directly through the property on the type, doing so does not implicitly trigger a render and the component life-cycle methods are not called. +> While it is possible to set `[Parameter]` and `[CascadingParameter]` properties directly through the property on the type, doing so does not implicitly trigger a render and the component life-cycle methods are not called. > -> The correct approach is to set parameters through the [`SetParametersAndRender()`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponentBase{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods. See the page for more on this. +> The correct approach is to set parameters through the [`SetParametersAndRender()`](xref:Bunit.RenderedComponentRenderExtensions.SetParametersAndRender``1(Bunit.IRenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods. See the page for more on this. ## Finding Components in the Render Tree diff --git a/src/bunit/Asserting/CompareToExtensions.cs b/src/bunit/Asserting/CompareToExtensions.cs index bb30c2137..5da74b14b 100644 --- a/src/bunit/Asserting/CompareToExtensions.cs +++ b/src/bunit/Asserting/CompareToExtensions.cs @@ -10,7 +10,7 @@ namespace Bunit; public static class CompareToExtensions { /// - /// Compare the rendered markup in the + /// Compare the rendered markup in the /// with that in the markup string. /// /// Source of rendered markup to check. @@ -28,8 +28,8 @@ public static IReadOnlyList CompareTo(this IRenderedFragment actual, stri } /// - /// Compare the rendered markup in the to - /// the rendered markup in the . + /// Compare the rendered markup in the to + /// the rendered markup in the . /// /// Source of rendered markup to check. /// Source of rendered markup to compare with. diff --git a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs index 8cb96e004..2228e5759 100644 --- a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs +++ b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs @@ -278,7 +278,7 @@ public static void MarkupMatches(this IRenderedFragment actual, RenderFragment e actual.Services.GetRequiredService(), actual.Services.GetRequiredService(), actual.Services.GetRequiredService()); - var renderedFragment = (IRenderedFragment)renderer.RenderFragment(expected); + var renderedFragment = renderer.RenderFragment(expected); MarkupMatches(actual, renderedFragment, userMessage); } @@ -414,7 +414,7 @@ public static void MarkupMatches(this IEnumerable actual, IEnumerable< private static IRenderedFragment AdhocRenderRenderFragment(this RenderFragment renderFragment) { using var ctx = new TestContext(); - return (IRenderedFragment)ctx.RenderInsideRenderTree(renderFragment); + return ctx.RenderInsideRenderTree(renderFragment); } private static INodeList ToNodeList(this string markup, BunitHtmlParser? htmlParser) diff --git a/src/bunit/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs b/src/bunit/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs index 17dc53538..1a433fa6e 100644 --- a/src/bunit/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs +++ b/src/bunit/ComponentFactories/GenericComponentFactory{TComponent,TSubstituteComponent}.cs @@ -2,9 +2,9 @@ namespace Bunit.ComponentFactories; internal sealed class GenericComponentFactory : IComponentFactory where TComponent : IComponent - where TSubstituteComponent : IComponent + where TSubstituteComponent : IComponent, new() { public bool CanCreate(Type componentType) => componentType == typeof(TComponent); - public IComponent Create(Type componentType) => Activator.CreateInstance()!; + public IComponent Create(Type componentType) => new TSubstituteComponent(); } diff --git a/src/bunit/Extensions/ComponentFactoryCollectionExtensions.cs b/src/bunit/Extensions/ComponentFactoryCollectionExtensions.cs index d17d27788..9bcf467e3 100644 --- a/src/bunit/Extensions/ComponentFactoryCollectionExtensions.cs +++ b/src/bunit/Extensions/ComponentFactoryCollectionExtensions.cs @@ -18,7 +18,7 @@ public static class ComponentFactoryCollectionExtensions /// A . public static ComponentFactoryCollection Add(this ComponentFactoryCollection factories) where TComponent : IComponent - where TSubstituteComponent : IComponent + where TSubstituteComponent : IComponent, new() { ArgumentNullException.ThrowIfNull(factories); diff --git a/src/bunit/Extensions/IRefreshableElementCollection.cs b/src/bunit/Extensions/IRefreshableElementCollection.cs index 285d0ee5b..5cc71a27e 100644 --- a/src/bunit/Extensions/IRefreshableElementCollection.cs +++ b/src/bunit/Extensions/IRefreshableElementCollection.cs @@ -4,7 +4,7 @@ namespace Bunit; /// /// Represents a collection, which queries and finds its -/// elements in an , based on a CSS selector. +/// elements in an , based on a CSS selector. /// The collection can be refreshed either manually or automatically. /// /// The type of in the collection. @@ -13,7 +13,7 @@ public interface IRefreshableElementCollection : IReadOnlyList { /// /// Gets or sets a value indicating whether the collection automatically refreshes when the - /// changes. + /// changes. /// bool EnableAutoRefresh { get; set; } diff --git a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs index a6de0a34b..a210d137f 100644 --- a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs @@ -4,7 +4,7 @@ namespace Bunit; /// -/// Re-render extension methods, optionally with new parameters, for . +/// Re-render extension methods, optionally with new parameters, for . /// public static class RenderedComponentRenderExtensions { @@ -13,7 +13,7 @@ public static class RenderedComponentRenderExtensions /// /// The rendered component to re-render. /// The type of the component. - public static void Render(this IRenderedComponentBase renderedComponent) + public static void Render(this IRenderedComponent renderedComponent) where TComponent : IComponent => SetParametersAndRender(renderedComponent, ParameterView.Empty); @@ -23,7 +23,7 @@ public static void Render(this IRenderedComponentBase re /// The rendered component to re-render with new parameters. /// Parameters to pass to the component upon rendered. /// The type of the component. - public static void SetParametersAndRender(this IRenderedComponentBase renderedComponent, ParameterView parameters) + public static void SetParametersAndRender(this IRenderedComponent renderedComponent, ParameterView parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); @@ -46,7 +46,7 @@ public static void SetParametersAndRender(this IRenderedComponentBas /// The rendered component to re-render with new parameters. /// Parameters to pass to the component upon rendered. /// The type of the component. - public static void SetParametersAndRender(this IRenderedComponentBase renderedComponent, params ComponentParameter[] parameters) + public static void SetParametersAndRender(this IRenderedComponent renderedComponent, params ComponentParameter[] parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); @@ -61,7 +61,7 @@ public static void SetParametersAndRender(this IRenderedComponentBas /// The rendered component to re-render with new parameters. /// An action that receives a . /// The type of the component. - public static void SetParametersAndRender(this IRenderedComponentBase renderedComponent, Action> parameterBuilder) + public static void SetParametersAndRender(this IRenderedComponent renderedComponent, Action> parameterBuilder) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); diff --git a/src/bunit/Extensions/RenderedFragmentExtensions.cs b/src/bunit/Extensions/RenderedFragmentExtensions.cs index af888b3f2..236b90bb2 100644 --- a/src/bunit/Extensions/RenderedFragmentExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentExtensions.cs @@ -56,7 +56,7 @@ public static IRenderedComponent FindComponent(this IRen ArgumentNullException.ThrowIfNull(renderedFragment); var renderer = renderedFragment.Services.GetRequiredService().Renderer; - return (IRenderedComponent)renderer.FindComponent(renderedFragment); + return renderer.FindComponent(renderedFragment); } /// diff --git a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index 6f0b6e04c..c95505202 100644 --- a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -3,7 +3,7 @@ namespace Bunit; /// -/// InvokeAsync extensions methods on . +/// InvokeAsync extensions methods on . /// public static class RenderedFragmentInvokeAsyncExtensions { @@ -13,7 +13,7 @@ public static class RenderedFragmentInvokeAsyncExtensions /// The rendered fragment whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing or is suspended by an asynchronous operation. - public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Action workItem) + public static Task InvokeAsync(this IRenderedFragment renderedFragment, Action workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -31,7 +31,7 @@ public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Acti /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing. - public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func workItem) + public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -49,7 +49,7 @@ public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing, with the return value from . - public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func workItem) + public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -67,7 +67,7 @@ public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing, with the return value from . - public static Task InvokeAsync(this IRenderedFragmentBase renderedFragment, Func> workItem) + public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func> workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); diff --git a/src/bunit/Extensions/TestContextBaseRenderExtensions.cs b/src/bunit/Extensions/TestContextBaseRenderExtensions.cs index 53c6abd49..88126a3c2 100644 --- a/src/bunit/Extensions/TestContextBaseRenderExtensions.cs +++ b/src/bunit/Extensions/TestContextBaseRenderExtensions.cs @@ -13,8 +13,8 @@ public static class TestContextBaseRenderExtensions /// The type of component to render. /// Test context to use to render with. /// The that contains a declaration of the component. - /// A . - public static IRenderedComponentBase RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) + /// A . + public static IRenderedComponent RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(testContext); @@ -28,8 +28,8 @@ public static IRenderedComponentBase RenderInsideRenderTree /// Test context to use to render with. /// The to render. - /// A . - public static IRenderedFragmentBase RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) + /// A . + public static IRenderedFragment RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) { ArgumentNullException.ThrowIfNull(testContext); diff --git a/src/bunit/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/TestServiceProviderExtensions.cs index c93faa0ec..40fca7ba0 100644 --- a/src/bunit/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit/Extensions/TestServiceProviderExtensions.cs @@ -31,7 +31,7 @@ public static IServiceCollection AddDefaultTestContextServices(this IServiceColl services.AddSingleton(); // bUnits fake JSInterop - services.AddSingleton(jsInterop.JSRuntime); + services.AddSingleton(jsInterop.JSRuntime); // bUnits fake Navigation Manager services.AddSingleton(); diff --git a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs index a270ebbbf..f2eb51d49 100644 --- a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs +++ b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs @@ -23,7 +23,7 @@ public static partial class RenderedFragmentWaitForHelperExtensions /// /// If a debugger is attached the timeout is set to , giving the possibility to debug without the timeout triggering. /// - public static void WaitForState(this IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) + public static void WaitForState(this IRenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) { using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); @@ -48,7 +48,7 @@ public static void WaitForState(this IRenderedFragmentBase renderedFragment, Fun /// The predicate to invoke after each render, which must returns true when the desired state has been reached. /// The maximum time to wait for the desired state. /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. - internal static async Task WaitForStateAsync(this IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) + internal static async Task WaitForStateAsync(this IRenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) { using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); @@ -66,7 +66,7 @@ internal static async Task WaitForStateAsync(this IRenderedFragmentBase rendered /// The maximum time to attempt the verification. /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. [AssertionMethod] - public static void WaitForAssertion(this IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) + public static void WaitForAssertion(this IRenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) { using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); @@ -91,7 +91,7 @@ public static void WaitForAssertion(this IRenderedFragmentBase renderedFragment, /// The maximum time to attempt the verification. /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. [AssertionMethod] - internal static async Task WaitForAssertionAsync(this IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) + internal static async Task WaitForAssertionAsync(this IRenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) { using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs index 95a9dcb80..a5e002a96 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs @@ -26,7 +26,7 @@ public class WaitForAssertionHelper : WaitForHelper /// /// If a debugger is attached the timeout is set to , giving the possibility to debug without the timeout triggering. /// - public WaitForAssertionHelper(IRenderedFragmentBase renderedFragment, Action assertion, TimeSpan? timeout = null) + public WaitForAssertionHelper(IRenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) : base( renderedFragment, () => diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index 033c8c27a..6e26324a6 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -5,7 +5,7 @@ namespace Bunit.Extensions.WaitForHelpers; /// -/// Represents a helper class that can wait for a render notifications from a type, +/// Represents a helper class that can wait for a render notifications from a type, /// until a specific timeout is reached. /// public abstract class WaitForHelper : IDisposable @@ -13,7 +13,7 @@ public abstract class WaitForHelper : IDisposable private readonly Timer timer; private readonly TaskCompletionSource checkPassedCompletionSource; private readonly Func<(bool CheckPassed, T Content)> completeChecker; - private readonly IRenderedFragmentBase renderedFragment; + private readonly IRenderedFragment renderedFragment; private readonly ILogger> logger; private readonly TestRenderer renderer; private bool isDisposed; @@ -46,7 +46,7 @@ public abstract class WaitForHelper : IDisposable /// Initializes a new instance of the class. /// protected WaitForHelper( - IRenderedFragmentBase renderedFragment, + IRenderedFragment renderedFragment, Func<(bool CheckPassed, T Content)> completeChecker, TimeSpan? timeout = null) { diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs index 0fe7f86a0..4ee219c02 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs @@ -29,7 +29,7 @@ public class WaitForStateHelper : WaitForHelper /// The predicate to invoke after each render, which must returns true when the desired state has been reached. /// The maximum time to wait for the desired state. /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. - public WaitForStateHelper(IRenderedFragmentBase renderedFragment, Func statePredicate, TimeSpan? timeout = null) + public WaitForStateHelper(IRenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) : base(renderedFragment, () => (statePredicate(), default), timeout) { } diff --git a/src/bunit/IRenderedComponent.cs b/src/bunit/IRenderedComponent.cs index 2326e23dc..175535f1c 100644 --- a/src/bunit/IRenderedComponent.cs +++ b/src/bunit/IRenderedComponent.cs @@ -1,7 +1,11 @@ namespace Bunit; /// -public interface IRenderedComponent : IRenderedComponentBase, IRenderedFragment +public interface IRenderedComponent : IRenderedFragment where TComponent : IComponent { + /// + /// Gets the component under test. + /// + TComponent Instance { get; } } diff --git a/src/bunit/IRenderedComponentBase.cs b/src/bunit/IRenderedComponentBase.cs deleted file mode 100644 index a09544827..000000000 --- a/src/bunit/IRenderedComponentBase.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Bunit; - -/// -/// Represents a rendered component-under-test. -/// -/// The type of the component under test. -public interface IRenderedComponentBase : IRenderedFragmentBase - where TComponent : IComponent -{ - /// - /// Gets the component under test. - /// - TComponent Instance { get; } -} diff --git a/src/bunit/IRenderedFragment.cs b/src/bunit/IRenderedFragment.cs index dcb6a0514..61a1a0192 100644 --- a/src/bunit/IRenderedFragment.cs +++ b/src/bunit/IRenderedFragment.cs @@ -1,15 +1,45 @@ -using AngleSharp.Diffing.Core; using AngleSharp.Dom; +using Bunit.Rendering; namespace Bunit; /// /// Represents a rendered fragment. /// -public interface IRenderedFragment : IRenderedFragmentBase +public interface IRenderedFragment : IDisposable { /// - /// An event that is raised after the markup of the is updated. + /// Gets the total number times the fragment has been through its render life-cycle. + /// + int RenderCount { get; } + + /// + /// Gets a value indicating whether the rendered component or fragment has been disposed by the . + /// + bool IsDisposed { get; } + + /// + /// Gets the id of the rendered component or fragment. + /// + int ComponentId { get; } + + /// + /// Called by the owning when it finishes a render. + /// + /// A that represents a render. + void OnRender(RenderEvent renderEvent); + + /// + /// Gets the used when rendering the component. + /// + IServiceProvider Services { get; } + + /// + /// Adds or removes an event handler that will be triggered after each render of this . + /// + event EventHandler OnAfterRender; + /// + /// An event that is raised after the markup of the is updated. /// event EventHandler OnMarkupUpdated; diff --git a/src/bunit/IRenderedFragmentBase.cs b/src/bunit/IRenderedFragmentBase.cs deleted file mode 100644 index 920bd73f9..000000000 --- a/src/bunit/IRenderedFragmentBase.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Bunit.Rendering; - -namespace Bunit; - -/// -/// Represents a rendered . -/// -public interface IRenderedFragmentBase : IDisposable -{ - /// - /// Gets the total number times the fragment has been through its render life-cycle. - /// - int RenderCount { get; } - - /// - /// Gets a value indicating whether the rendered component or fragment has been disposed by the . - /// - bool IsDisposed { get; } - - /// - /// Gets the id of the rendered component or fragment. - /// - int ComponentId { get; } - - /// - /// Called by the owning when it finishes a render. - /// - /// A that represents a render. - void OnRender(RenderEvent renderEvent); - - /// - /// Gets the used when rendering the component. - /// - IServiceProvider Services { get; } - - /// - /// Adds or removes an event handler that will be triggered after each render of this . - /// - event EventHandler OnAfterRender; -} diff --git a/src/bunit/Rendering/ComponentDisposedException.cs b/src/bunit/Rendering/ComponentDisposedException.cs index 9ffb6cbd9..634d311f1 100644 --- a/src/bunit/Rendering/ComponentDisposedException.cs +++ b/src/bunit/Rendering/ComponentDisposedException.cs @@ -1,7 +1,7 @@ namespace Bunit.Rendering; /// -/// Represents an exception that is thrown when a 's +/// Represents an exception that is thrown when a 's /// properties is accessed after the underlying component has been disposed by the renderer. /// [Serializable] diff --git a/src/bunit/Rendering/IRenderedComponentActivator.cs b/src/bunit/Rendering/IRenderedComponentActivator.cs index f5593575b..faf6b36dd 100644 --- a/src/bunit/Rendering/IRenderedComponentActivator.cs +++ b/src/bunit/Rendering/IRenderedComponentActivator.cs @@ -1,25 +1,25 @@ namespace Bunit.Rendering; /// -/// Represents an activator for and types. +/// Represents an activator for and types. /// public interface IRenderedComponentActivator { /// - /// Creates an with the specified . + /// Creates an with the specified . /// - IRenderedFragmentBase CreateRenderedFragment(int componentId); + IRenderedFragment CreateRenderedFragment(int componentId); /// - /// Creates an with the specified . + /// Creates an with the specified . /// - IRenderedComponentBase CreateRenderedComponent(int componentId) + IRenderedComponent CreateRenderedComponent(int componentId) where TComponent : IComponent; /// - /// Creates an with the specified , + /// Creates an with the specified , /// , and . /// - IRenderedComponentBase CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) + IRenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) where TComponent : IComponent; } diff --git a/src/bunit/Rendering/ITestRenderer.cs b/src/bunit/Rendering/ITestRenderer.cs index 50f8d3e72..5e445dec0 100644 --- a/src/bunit/Rendering/ITestRenderer.cs +++ b/src/bunit/Rendering/ITestRenderer.cs @@ -46,16 +46,16 @@ Task DispatchEventAsync( /// Renders the . ///
    /// The to render. - /// A that provides access to the rendered . - IRenderedFragmentBase RenderFragment(RenderFragment renderFragment); + /// A that provides access to the rendered . + IRenderedFragment RenderFragment(RenderFragment renderFragment); /// /// Renders a with the passed to it. /// /// The type of component to render. /// The parameters to pass to the component. - /// A that provides access to the rendered component. - IRenderedComponentBase RenderComponent(ComponentParameterCollection parameters) + /// A that provides access to the rendered component. + IRenderedComponent RenderComponent(ComponentParameterCollection parameters) where TComponent : IComponent; /// @@ -63,7 +63,7 @@ IRenderedComponentBase RenderComponent(ComponentParamete /// /// Type of component to find. /// Parent component to search. - IRenderedComponentBase FindComponent(IRenderedFragmentBase parentComponent) + IRenderedComponent FindComponent(IRenderedFragment parentComponent) where TComponent : IComponent; /// @@ -71,7 +71,7 @@ IRenderedComponentBase FindComponent(IRenderedFragmentBa /// /// Type of components to find. /// Parent component to search. - IReadOnlyList> FindComponents(IRenderedFragmentBase parentComponent) + IReadOnlyList> FindComponents(IRenderedFragment parentComponent) where TComponent : IComponent; /// diff --git a/src/bunit/Rendering/RenderEvent.cs b/src/bunit/Rendering/RenderEvent.cs index bbb410653..cd8561e16 100644 --- a/src/bunit/Rendering/RenderEvent.cs +++ b/src/bunit/Rendering/RenderEvent.cs @@ -20,7 +20,7 @@ public sealed class RenderEvent /// /// The to get the status for. /// A tuple of statuses indicating whether the rendered component rendered during the render cycle, if it changed or if it was disposed. - public (bool Rendered, bool Changed, bool Disposed) GetRenderStatus(IRenderedFragmentBase renderedComponent) + public (bool Rendered, bool Changed, bool Disposed) GetRenderStatus(IRenderedFragment renderedComponent) { ArgumentNullException.ThrowIfNull(renderedComponent); diff --git a/src/bunit/Rendering/RenderedComponentActivator.cs b/src/bunit/Rendering/RenderedComponentActivator.cs index 23b2e944c..a557c2073 100644 --- a/src/bunit/Rendering/RenderedComponentActivator.cs +++ b/src/bunit/Rendering/RenderedComponentActivator.cs @@ -16,16 +16,16 @@ public RenderedComponentActivator(IServiceProvider services) } /// - public IRenderedFragmentBase CreateRenderedFragment(int componentId) + public IRenderedFragment CreateRenderedFragment(int componentId) => new RenderedFragment(componentId, services); /// - public IRenderedComponentBase CreateRenderedComponent(int componentId) + public IRenderedComponent CreateRenderedComponent(int componentId) where TComponent : IComponent => new RenderedComponent(componentId, services); /// - public IRenderedComponentBase CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) + public IRenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) where TComponent : IComponent => new RenderedComponent(componentId, component, componentFrames, services); } diff --git a/src/bunit/Rendering/RenderedFragment.cs b/src/bunit/Rendering/RenderedFragment.cs index e643e58d4..8b5e30785 100644 --- a/src/bunit/Rendering/RenderedFragment.cs +++ b/src/bunit/Rendering/RenderedFragment.cs @@ -78,7 +78,7 @@ internal RenderedFragment(int componentId, IServiceProvider service) htmlParser = Services.GetRequiredService(); } - void IRenderedFragmentBase.OnRender(RenderEvent renderEvent) + void IRenderedFragment.OnRender(RenderEvent renderEvent) { if (IsDisposed) return; diff --git a/src/bunit/Rendering/TestRenderer.cs b/src/bunit/Rendering/TestRenderer.cs index f78298ffc..06e787d62 100644 --- a/src/bunit/Rendering/TestRenderer.cs +++ b/src/bunit/Rendering/TestRenderer.cs @@ -17,7 +17,7 @@ public class TestRenderer : Renderer, ITestRenderer extern static void CallSetDirectParameters(ComponentState componentState, ParameterView parameters); private readonly object renderTreeUpdateLock = new(); - private readonly Dictionary renderedComponents = new(); + private readonly Dictionary renderedComponents = new(); private readonly List rootComponents = new(); private readonly ILogger logger; private readonly IRenderedComponentActivator activator; @@ -57,7 +57,8 @@ public TestRenderer(IRenderedComponentActivator renderedComponentActivator, Test : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), null)) { logger = loggerFactory.CreateLogger(); - this.activator = renderedComponentActivator; + activator = renderedComponentActivator; + ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } /// @@ -67,15 +68,16 @@ public TestRenderer(IRenderedComponentActivator renderedComponentActivator, Test : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), componentActivator)) { logger = loggerFactory.CreateLogger(); - this.activator = renderedComponentActivator; + activator = renderedComponentActivator; + ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } /// - public IRenderedFragmentBase RenderFragment(RenderFragment renderFragment) + public IRenderedFragment RenderFragment(RenderFragment renderFragment) => Render(renderFragment, id => activator.CreateRenderedFragment(id)); /// - public IRenderedComponentBase RenderComponent(ComponentParameterCollection parameters) + public IRenderedComponent RenderComponent(ComponentParameterCollection parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(parameters); @@ -141,7 +143,7 @@ public IRenderedComponentBase RenderComponent(ComponentP } /// - public IRenderedComponentBase FindComponent(IRenderedFragmentBase parentComponent) + public IRenderedComponent FindComponent(IRenderedFragment parentComponent) where TComponent : IComponent { var foundComponents = FindComponents(parentComponent, 1); @@ -151,7 +153,7 @@ public IRenderedComponentBase FindComponent(IRenderedFra } /// - public IReadOnlyList> FindComponents(IRenderedFragmentBase parentComponent) + public IReadOnlyList> FindComponents(IRenderedFragment parentComponent) where TComponent : IComponent => FindComponents(parentComponent, int.MaxValue); @@ -191,7 +193,7 @@ protected override IComponent ResolveComponentForRenderMode(Type componentType, } /// - internal Task SetDirectParametersAsync(IRenderedFragmentBase renderedComponent, ParameterView parameters) + internal Task SetDirectParametersAsync(IRenderedFragment renderedComponent, ParameterView parameters) { ObjectDisposedException.ThrowIf(disposed, this); @@ -399,7 +401,7 @@ protected override void Dispose(bool disposing) } private TResult Render(RenderFragment renderFragment, Func activator) - where TResult : IRenderedFragmentBase + where TResult : IRenderedFragment { ObjectDisposedException.ThrowIf(disposed, this); @@ -435,14 +437,14 @@ private TResult Render(RenderFragment renderFragment, Func> FindComponents(IRenderedFragmentBase parentComponent, int resultLimit) + private List> FindComponents(IRenderedFragment parentComponent, int resultLimit) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(parentComponent); ObjectDisposedException.ThrowIf(disposed, this); - var result = new List>(); + var result = new List>(); var framesCollection = new RenderTreeFrameDictionary(); // Blocks the renderer from changing the render tree @@ -482,12 +484,12 @@ void FindComponentsInRenderTree(int componentId) } } - private IRenderedComponentBase GetOrCreateRenderedComponent(RenderTreeFrameDictionary framesCollection, int componentId, TComponent component) + private IRenderedComponent GetOrCreateRenderedComponent(RenderTreeFrameDictionary framesCollection, int componentId, TComponent component) where TComponent : IComponent { if (renderedComponents.TryGetValue(componentId, out var renderedComponent)) { - return (IRenderedComponentBase)renderedComponent; + return (IRenderedComponent)renderedComponent; } LoadRenderTreeFrames(componentId, framesCollection); diff --git a/src/bunit/Rendering/WebTestRenderer.cs b/src/bunit/Rendering/WebTestRenderer.cs deleted file mode 100644 index 3a9a87a4b..000000000 --- a/src/bunit/Rendering/WebTestRenderer.cs +++ /dev/null @@ -1,28 +0,0 @@ -using Microsoft.Extensions.Logging; - -namespace Bunit.Rendering; - -/// -/// Represents a that is used when rendering -/// Blazor components for the web. -/// -public class WebTestRenderer : TestRenderer -{ - /// - /// Initializes a new instance of the class. - /// - public WebTestRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory) - : base(renderedComponentActivator, services, loggerFactory) - { - ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); - } - - /// - /// Initializes a new instance of the class. - /// - public WebTestRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) - : base(renderedComponentActivator, services, loggerFactory, componentActivator) - { - ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); - } -} diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index a0ada8011..afcb45ff9 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -65,7 +65,7 @@ public virtual IRenderedComponent RenderComponent(Action /// The . public virtual IRenderedComponent Render(RenderFragment renderFragment) where TComponent : IComponent - => (IRenderedComponent)this.RenderInsideRenderTree(renderFragment); + => this.RenderInsideRenderTree(renderFragment); /// /// Renders the and returns it as a . @@ -73,7 +73,7 @@ public virtual IRenderedComponent Render(RenderFragment /// The render fragment to render. /// The . public virtual IRenderedFragment Render(RenderFragment renderFragment) - => (IRenderedFragment)this.RenderInsideRenderTree(renderFragment); + => this.RenderInsideRenderTree(renderFragment); /// /// Dummy method required to allow Blazor's compiler to generate @@ -89,7 +89,7 @@ protected override ITestRenderer CreateTestRenderer() var componentActivator = Services.GetService(); return componentActivator is null - ? new WebTestRenderer(renderedComponentActivator, Services, logger) - : new WebTestRenderer(renderedComponentActivator, Services, logger, componentActivator); + ? new TestRenderer(renderedComponentActivator, Services, logger) + : new TestRenderer(renderedComponentActivator, Services, logger, componentActivator); } } diff --git a/src/bunit/TestContextBase.cs b/src/bunit/TestContextBase.cs index cd660e5f8..95e999590 100644 --- a/src/bunit/TestContextBase.cs +++ b/src/bunit/TestContextBase.cs @@ -11,7 +11,7 @@ public abstract class TestContextBase : IDisposable private ITestRenderer? testRenderer; /// - /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . + /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . /// /// The default is 1 second. public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); diff --git a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs index fcce39230..77a60513d 100644 --- a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs +++ b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs @@ -39,13 +39,13 @@ private async Task VerifyEventCallbackAsync(string expectedName) private IRenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) { - return (IRenderedFragment)Renderer.RenderFragment(renderFragment); + return Renderer.RenderFragment(renderFragment); } private IRenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) where TComponent : IComponent { - var res = (IRenderedFragment)Renderer.RenderFragment(renderFragment); + var res = Renderer.RenderFragment(renderFragment); return res.FindComponent(); } diff --git a/tests/bunit.tests/ComponentParameterCollectionTest.cs b/tests/bunit.tests/ComponentParameterCollectionTest.cs index 6a809a206..99b0250b6 100644 --- a/tests/bunit.tests/ComponentParameterCollectionTest.cs +++ b/tests/bunit.tests/ComponentParameterCollectionTest.cs @@ -4,7 +4,7 @@ public class ComponentParameterCollectionTest : TestContext { private IRenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) { - var res = (IRenderedFragment)Renderer.RenderFragment(renderFragment); + var res = Renderer.RenderFragment(renderFragment); return res.FindComponent(); } diff --git a/tests/bunit.tests/ComponentParameterFactoryTest.cs b/tests/bunit.tests/ComponentParameterFactoryTest.cs index e642e2317..d3dc660d5 100644 --- a/tests/bunit.tests/ComponentParameterFactoryTest.cs +++ b/tests/bunit.tests/ComponentParameterFactoryTest.cs @@ -10,7 +10,7 @@ public class ComponentParameterFactoryTest private static IRenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) { - return (IRenderedFragment)Context.Renderer.RenderFragment(renderFragment); + return Context.Renderer.RenderFragment(renderFragment); } private string? Actual { get; set; } diff --git a/tests/bunit.tests/Rendering/TestRendererTest.cs b/tests/bunit.tests/Rendering/TestRendererTest.cs index d7347b509..a4e1ecf2f 100644 --- a/tests/bunit.tests/Rendering/TestRendererTest.cs +++ b/tests/bunit.tests/Rendering/TestRendererTest.cs @@ -38,7 +38,7 @@ public void Test001() const string MARKUP = "

    hello world

    "; using var sut = CreateRenderer(); - var cut = (IRenderedFragment)sut.RenderFragment(builder => builder.AddMarkupContent(0, MARKUP)); + var cut = sut.RenderFragment(builder => builder.AddMarkupContent(0, MARKUP)); cut.RenderCount.ShouldBe(1); cut.Markup.ShouldBe(MARKUP); @@ -129,7 +129,7 @@ public void Test020() ChildContent((nameof(HasParams.Value), CHILD_VALUE))); // act - var childCut = (IRenderedComponent)sut.FindComponent(cut); + var childCut = sut.FindComponent(cut); // assert childCut.Markup.ShouldBe(CHILD_VALUE); @@ -231,7 +231,7 @@ public async Task Test040() ChildContent()); // act - var cut = (IRenderedComponent)sut.FindComponent(parent); + var cut = sut.FindComponent(parent); cut.RenderCount.ShouldBe(1); @@ -250,7 +250,7 @@ public async Task Test041() ChildContent()); // act - var cut = (IRenderedComponent)sut.FindComponents(parent).Single(); + var cut = sut.FindComponents(parent).Single(); cut.RenderCount.ShouldBe(1); @@ -268,7 +268,7 @@ public async Task Test050() var cut = sut.RenderComponent( ChildContent()); - var child = (IRenderedComponent)sut.FindComponent(cut); + var child = sut.FindComponent(cut); // act await child.Instance.TriggerWithValue("X"); @@ -286,7 +286,7 @@ public async Task Test060() var cut = sut.RenderComponent( ChildContent()); - var child = (IRenderedComponent)sut.FindComponent(cut); + var child = sut.FindComponent(cut); // act await cut.Instance.DisposeChild(); @@ -305,8 +305,8 @@ public async Task Test061() var cut = sut.RenderComponent( ChildContent( ChildContent())); - var child = (IRenderedComponent)sut.FindComponent(cut); - var childChild = (IRenderedComponent)sut.FindComponent(cut); + var child = sut.FindComponent(cut); + var childChild = sut.FindComponent(cut); // act await child.Instance.DisposeChild(); @@ -319,7 +319,7 @@ public async Task Test061() [Fact(DisplayName = "When test renderer is disposed, so is all rendered components")] public void Test070() { - var sut = (TestRenderer)CreateRenderer(); + var sut = CreateRenderer(); var cut = sut.RenderComponent(); sut.Dispose(); @@ -514,7 +514,7 @@ public void Test211() cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveWebAssembly}"); } - private WebTestRenderer CreateRenderer() => new WebTestRenderer( + private TestRenderer CreateRenderer() => new TestRenderer( Services.GetRequiredService(), Services, NullLoggerFactory.Instance); From c5402c46e8d7950f2c7b0726f70859cfd26e255b Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 10:51:50 +0100 Subject: [PATCH 008/100] refactor: Rename Fake to Bunit --- MIGRATION.md | 6 ++ .../tests/xunit/InjectAuthServiceTest.cs | 4 +- docs/samples/tests/xunit/UserInfoTest.cs | 8 +- docs/samples/tests/xunit/UserRightsTest.cs | 16 ++-- .../passing-parameters-to-components.md | 2 +- .../test-doubles/{faking-auth.md => auth.md} | 20 ++--- .../fake-webassemblyhostenvironment.md | 16 ++-- docs/site/docs/test-doubles/index.md | 8 +- ...ation-manager.md => navigation-manager.md} | 20 ++--- ...ntstate.md => persistentcomponentstate.md} | 42 +++++----- docs/site/docs/toc.md | 8 +- .../TestServiceProviderExtensions.cs | 18 ++--- ...cs => BunitAuthenticationStateProvider.cs} | 14 ++-- ...ons.cs => BunitAuthorizationExtensions.cs} | 8 +- ...cs => BunitAuthorizationPolicyProvider.cs} | 2 +- ...ervice.cs => BunitAuthorizationService.cs} | 6 +- ... => MissingBunitAuthorizationException.cs} | 12 +-- .../PlaceholderAuthenticationStateProvider.cs | 2 +- .../PlaceholderAuthorizationService.cs | 4 +- .../Authorization/TestAuthorizationContext.cs | 6 +- ...tion.cs => BunitNavigationInterception.cs} | 2 +- ...onManager.cs => BunitNavigationManager.cs} | 13 ++-- ....cs => BunitSignOutSessionStateManager.cs} | 8 +- ...te.cs => BunitPersistentComponentState.cs} | 18 ++--- ... => BunitPersistentComponentStateStore.cs} | 2 +- .../TestContextBaseExtensions.cs | 12 +-- ....cs => BunitWebAssemblyHostEnvironment.cs} | 5 +- .../Authorization/AuthorizationTest.cs | 40 +++++----- ...> BunitAuthenticationStateProviderTest.cs} | 8 +- ...> BunitAuthorizationPolicyProviderTest.cs} | 12 +-- ...st.cs => BunitAuthorizationServiceTest.cs} | 14 ++-- .../TestAuthorizationContextTest.cs | 12 +-- ...=> BunitSignOutSessionStateManagerTest.cs} | 8 +- ...=> BunitWebAssemblyHostEnvironmentTest.cs} | 6 +- ....cs => BunitNavigationInterceptionTest.cs} | 6 +- ...rTest.cs => BunitNavigationManagerTest.cs} | 78 +++++++++---------- ...s => BunitPersistentComponentStateTest.cs} | 30 +++---- 37 files changed, 250 insertions(+), 246 deletions(-) rename docs/site/docs/test-doubles/{faking-auth.md => auth.md} (71%) rename docs/site/docs/test-doubles/{fake-navigation-manager.md => navigation-manager.md} (84%) rename docs/site/docs/test-doubles/{faking-persistentcomponentstate.md => persistentcomponentstate.md} (61%) rename src/bunit/TestDoubles/Authorization/{FakeAuthenticationStateProvider.cs => BunitAuthenticationStateProvider.cs} (90%) rename src/bunit/TestDoubles/Authorization/{FakeAuthorizationExtensions.cs => BunitAuthorizationExtensions.cs} (79%) rename src/bunit/TestDoubles/Authorization/{FakeAuthorizationPolicyProvider.cs => BunitAuthorizationPolicyProvider.cs} (95%) rename src/bunit/TestDoubles/Authorization/{FakeAuthorizationService.cs => BunitAuthorizationService.cs} (94%) rename src/bunit/TestDoubles/Authorization/{MissingFakeAuthorizationException.cs => MissingBunitAuthorizationException.cs} (62%) rename src/bunit/TestDoubles/NavigationInterception/{FakeNavigationInterception.cs => BunitNavigationInterception.cs} (66%) rename src/bunit/TestDoubles/NavigationManager/{FakeNavigationManager.cs => BunitNavigationManager.cs} (86%) rename src/bunit/TestDoubles/NavigationManager/{FakeSignOutSessionStateManager.cs => BunitSignOutSessionStateManager.cs} (67%) rename src/bunit/TestDoubles/PersistentComponentState/{FakePersistentComponentState.cs => BunitPersistentComponentState.cs} (87%) rename src/bunit/TestDoubles/PersistentComponentState/{FakePersistentComponentStateStore.cs => BunitPersistentComponentStateStore.cs} (85%) rename src/bunit/TestDoubles/WebAssemblyHostEnvironment/{FakeWebAssemblyHostEnvironment.cs => BunitWebAssemblyHostEnvironment.cs} (81%) rename tests/bunit.tests/TestDoubles/Authorization/{FakeAuthenticationStateProviderTest.cs => BunitAuthenticationStateProviderTest.cs} (85%) rename tests/bunit.tests/TestDoubles/Authorization/{FakeAuthorizationPolicyProviderTest.cs => BunitAuthorizationPolicyProviderTest.cs} (85%) rename tests/bunit.tests/TestDoubles/Authorization/{FakeAuthorizationServiceTest.cs => BunitAuthorizationServiceTest.cs} (83%) rename tests/bunit.tests/TestDoubles/{FakeSignOutSessionStateManagerTest.cs => BunitSignOutSessionStateManagerTest.cs} (64%) rename tests/bunit.tests/TestDoubles/{FakeWebAssemblyHostEnvironmentTest.cs => BunitWebAssemblyHostEnvironmentTest.cs} (73%) rename tests/bunit.tests/TestDoubles/NavigationManager/{FakeNavigationInterceptionTest.cs => BunitNavigationInterceptionTest.cs} (77%) rename tests/bunit.tests/TestDoubles/NavigationManager/{FakeNavigationManagerTest.cs => BunitNavigationManagerTest.cs} (80%) rename tests/bunit.tests/TestDoubles/PersistentComponentState/{FakePersistentComponentStateTest.cs => BunitPersistentComponentStateTest.cs} (58%) diff --git a/MIGRATION.md b/MIGRATION.md index fa9dd9e0d..cbafd337b 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -33,3 +33,9 @@ The `bunit.core` and `bunit.web` packages have been merged into a single `bunit` ### `WebTestRender` merged into `TestRender` The `WebTestRender` class has been merged into the `TestRender` class. If you used `WebTestRender`, you should replace it with `TestRender`. + +## Renamed `Fake` to `Bunit` in many test doubles +The `Fake` prefix has been replaced with `Bunit` in many test doubles. For example, `FakeNavigationManager` is now `BunitNavigationManager`. If you reference any of these types explicitly, you need to update your code. + +### Renamed `AddTestAuthorization` to `AddAuthorization` +The `AddTestAuthorization` method on `TestContext` has been renamed to `AddAuthorization`. If you used `AddTestAuthorization`, you should replace it with `AddAuthorization`. diff --git a/docs/samples/tests/xunit/InjectAuthServiceTest.cs b/docs/samples/tests/xunit/InjectAuthServiceTest.cs index c7a4d72eb..aa3bebc87 100644 --- a/docs/samples/tests/xunit/InjectAuthServiceTest.cs +++ b/docs/samples/tests/xunit/InjectAuthServiceTest.cs @@ -10,7 +10,7 @@ public class InjectAuthServiceTest : TestContext public void Test001() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUserName", AuthorizationState.Authorized); // act @@ -24,7 +24,7 @@ public void Test001() public void Test002() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); // act var cut = RenderComponent(); diff --git a/docs/samples/tests/xunit/UserInfoTest.cs b/docs/samples/tests/xunit/UserInfoTest.cs index c3616cd86..080e7cef0 100644 --- a/docs/samples/tests/xunit/UserInfoTest.cs +++ b/docs/samples/tests/xunit/UserInfoTest.cs @@ -9,7 +9,7 @@ public class UserInfoTest : TestContext public void Test001() { // Arrange - this.AddTestAuthorization(); + this.AddAuthorization(); // Act var cut = RenderComponent(); @@ -23,7 +23,7 @@ public void Test001() public void Test004() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorizing(); // Act @@ -38,7 +38,7 @@ public void Test004() public void Test002() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER", AuthorizationState.Unauthorized); // Act @@ -53,7 +53,7 @@ public void Test002() public void Test003() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); // Act diff --git a/docs/samples/tests/xunit/UserRightsTest.cs b/docs/samples/tests/xunit/UserRightsTest.cs index 3e3f82a2c..41d290701 100644 --- a/docs/samples/tests/xunit/UserRightsTest.cs +++ b/docs/samples/tests/xunit/UserRightsTest.cs @@ -11,7 +11,7 @@ public class UserRightsTest : TestContext public void Test001() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); // Act @@ -26,7 +26,7 @@ public void Test001() public void Test002() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetRoles("superuser"); @@ -44,7 +44,7 @@ public void Test002() public void Test003() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetRoles("admin", "superuser"); @@ -63,7 +63,7 @@ public void Test003() public void Test004() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetPolicies("content-editor"); @@ -81,7 +81,7 @@ public void Test004() public void Test0041() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetPolicies("content-editor", "approver"); @@ -99,7 +99,7 @@ public void Test0041() public void Test006() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetClaims( new Claim(ClaimTypes.Email, "test@example.com"), @@ -121,7 +121,7 @@ public void Test006() public void Test005() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetRoles("admin", "superuser"); authContext.SetPolicies("content-editor"); @@ -144,7 +144,7 @@ public void Test005() public void Test007() { // Arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetAuthenticationType("custom-auth-type"); diff --git a/docs/site/docs/providing-input/passing-parameters-to-components.md b/docs/site/docs/providing-input/passing-parameters-to-components.md index 4db2fccf1..a0a5be316 100644 --- a/docs/site/docs/providing-input/passing-parameters-to-components.md +++ b/docs/site/docs/providing-input/passing-parameters-to-components.md @@ -469,7 +469,7 @@ When rendering a `RenderFragment` using the 's `Add` method, if a component parameter is only annotated with the `[SupplyParameterFromQuery]` attribute. Instead, pass a query string parameters by setting it using the . +In .NET 8 however, the `[Parameter]` attribute is no longer required, which means a value cannot be passed to the component during testing using the normal methods, e.g. the 's `Add` method, if a component parameter is only annotated with the `[SupplyParameterFromQuery]` attribute. Instead, pass a query string parameters by setting it using the . For example: diff --git a/docs/site/docs/test-doubles/faking-auth.md b/docs/site/docs/test-doubles/auth.md similarity index 71% rename from docs/site/docs/test-doubles/faking-auth.md rename to docs/site/docs/test-doubles/auth.md index dd0d1a584..8a94cb728 100644 --- a/docs/site/docs/test-doubles/faking-auth.md +++ b/docs/site/docs/test-doubles/auth.md @@ -1,9 +1,9 @@ --- -uid: faking-auth -title: Faking authentication and authorization +uid: bunit-auth +title: Adding authentication and authorization --- -# Faking authentication and authorization +# Adding authentication and authorization bUnit comes with test-specific implementations of Blazor's authentication and authorization types, making it easy to test components that use Blazor's ``, `` and `` components, as well as the `AuthenticationStateProvider` type. @@ -15,10 +15,10 @@ The test implementation of Blazor's authentication and authorization can be put - **Authenticated** and **authorized** - **Authenticated** and **authorized** with one or more **roles**, **claims**, and/or **policies** -bUnit's authentication and authorization implementation is easily available by calling [`AddTestAuthorization()`](xref:Bunit.TestDoubles.FakeAuthorizationExtensions.AddTestAuthorization(Bunit.TestContextBase)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. +bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContextBase)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. > [!NOTE] -> If your test class inherits directly from bUnit's then you need to call the [`AddTestAuthorization()`](xref:Bunit.TestDoubles.FakeAuthorizationExtensions.AddTestAuthorization(Bunit.TestContextBase)) method on `this`, since `AddTestAuthorization()` is an extension method, otherwise it wont be available. E.g.: `this.AddTestAuthorization()`. +> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContextBase)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `this.AddAuthorization()`. The following sections show how to set each of these states in a test. @@ -36,9 +36,9 @@ To set the state to unauthenticated and unauthorized, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=11&end=19&highlight=2)] -The highlighted line shows how `AddTestAuthorization()` is used to add the test-specific implementation of Blazor's authentication and authorization types to the `Services` collection, which makes the authentication state available to other services as well as components used throughout the test that require it. +The highlighted line shows how `AddAuthorization()` is used to add the test-specific implementation of Blazor's authentication and authorization types to the `Services` collection, which makes the authentication state available to other services as well as components used throughout the test that require it. -After calling `AddTestAuthorization()`, the default authentication state is unauthenticated and unauthorized. +After calling `AddAuthorization()`, the default authentication state is unauthenticated and unauthorized. ### Authenticating and authorizing state @@ -46,7 +46,7 @@ To set the state to authenticating and authorizing, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=25&end=34&highlight=3)] -After calling `AddTestAuthorization()`, the returned is used to set the authenticating and authorizing state through the method. +After calling `AddAuthorization()`, the returned is used to set the authenticating and authorizing state through the method. ### Authenticated and unauthorized state @@ -54,7 +54,7 @@ To set the state to authenticated and unauthorized, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=40&end=49&highlight=3)] -After calling `AddTestAuthorization()`, the returned is used to set the authenticated and unauthorized state through the method. +After calling `AddAuthorization()`, the returned is used to set the authenticated and unauthorized state through the method. ### Authenticated and authorized state @@ -62,7 +62,7 @@ To set the state to authenticated and authorized, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=55&end=64&highlight=3)] -After calling `AddTestAuthorization()`, the returned is used to set the authenticated and authorized state through the method. +After calling `AddAuthorization()`, the returned is used to set the authenticated and authorized state through the method. Note that the second parameter, `AuthorizationState`, is optional, and defaults to `AuthorizationState.Authorized` if not specified. diff --git a/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md b/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md index edd86fe72..9bb8d5a95 100644 --- a/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md +++ b/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md @@ -1,17 +1,17 @@ --- -uid: fake-webassemblyhostenvironment -title: Faking IWebAssemblyHostEnvironment +uid: bunit-webassemblyhostenvironment +title: Adding IWebAssemblyHostEnvironment --- -# Faking `IWebAssemblyHostEnvironment` +# Adding `IWebAssemblyHostEnvironment` -bUnit has a fake implementation of Blazor's `IWebAssemblyHostEnvironment` built-in, which is added by default to bUnit's `TestContext.Services` service provider. That means nothing special is needed to test components that depend on `IWebAssemblyHostEnvironment`, as it is already available by default. +bUnit has itws own implementation of Blazor's `IWebAssemblyHostEnvironment` built-in, which is added by default to bUnit's `TestContext.Services` service provider. That means nothing special is needed to test components that depend on `IWebAssemblyHostEnvironment`, as it is already available by default. -Out of the box, the fake implementation has its `Environment` property set to `production`, and its `BaseAddress` set to `/`. +Out of the box, the implementation has its `Environment` property set to `production`, and its `BaseAddress` set to `/`. ## Setting `Environment` and `BaseAddress` -Lets look at a few examples of how to set the two `IWebAssemblyHostEnvironment` properties `Environment` and `BaseAddress` via the built-in fake. +Lets look at a few examples of how to set the two `IWebAssemblyHostEnvironment` properties `Environment` and `BaseAddress` via the built-in object. In the examples, we'll use the following `` component: @@ -30,7 +30,7 @@ To verify that the `` component correctly says hello to the develope ```csharp // Arrange -var hostEnvironment = Services.GetRequiredService(); +var hostEnvironment = Services.GetRequiredService(); // Sets the environment to "Development". There are two other helper // methods available as well, SetEnvironmentToProduction() and @@ -48,7 +48,7 @@ To verify that the `` component correctly uses the current `BaseAddr ```csharp // Arrange -var hostEnvironment = Services.GetRequiredService(); +var hostEnvironment = Services.GetRequiredService(); // Sets a new base address directly on the BaseAddress property. hostEnvironment.BaseAddress = "myBaseUrl/"; diff --git a/docs/site/docs/test-doubles/index.md b/docs/site/docs/test-doubles/index.md index 88a1de589..033af3063 100644 --- a/docs/site/docs/test-doubles/index.md +++ b/docs/site/docs/test-doubles/index.md @@ -11,10 +11,10 @@ bUnit does, however, come with a few specially crafted test doubles for some of The built-in test doubles are described on the following pages: -- +- - - -- -- -- +- +- +- - \ No newline at end of file diff --git a/docs/site/docs/test-doubles/fake-navigation-manager.md b/docs/site/docs/test-doubles/navigation-manager.md similarity index 84% rename from docs/site/docs/test-doubles/fake-navigation-manager.md rename to docs/site/docs/test-doubles/navigation-manager.md index ab7f425f0..f4eb7ac00 100644 --- a/docs/site/docs/test-doubles/fake-navigation-manager.md +++ b/docs/site/docs/test-doubles/navigation-manager.md @@ -1,11 +1,11 @@ --- -uid: fake-navigation-manager -title: Faking NavigationManager +uid: bunit-navigation-manager +title: Adding NavigationManager --- -# Faking `NavigationManager` +# Adding `NavigationManager` -bUnit has a fake version of Blazor's `NavigationManager` built-in, which is added by default to bUnit's `TestContext.Services` service provider. That means nothing special is needed to test components that depend on `NavigationManager`, as it is already available by default. +bUnit has its own version of Blazor's `NavigationManager` built-in, which is added by default to bUnit's `TestContext.Services` service provider. That means nothing special is needed to test components that depend on `NavigationManager`, as it is already available by default. ## Verify `NavigationManager` interactions @@ -43,7 +43,7 @@ To verify that the `` component correctly listens to location c ```csharp // Arrange -var navMan = Services.GetRequiredService(); +var navMan = Services.GetRequiredService(); var cut = RenderComponent(); // Act - trigger a navigation change @@ -64,11 +64,11 @@ var cut = RenderComponent(parameters => parameters cut.Find("button").Click(); // Assert - inspect the navigation manager to see if its Uri has been updated. -var navMan = Services.GetRequiredService(); +var navMan = Services.GetRequiredService(); Assert.Equal("http://localhost/foo", navMan.Uri); ``` -If a component issues multiple `NavigateTo` calls, then it is possible to inspect the navigation history by accessing the property. It's a stack based structure, meaning the latest navigations will be first in the collection at index 0. +If a component issues multiple `NavigateTo` calls, then it is possible to inspect the navigation history by accessing the property. It's a stack based structure, meaning the latest navigations will be first in the collection at index 0. ## Asserting that navigation was prevented with the `NavigationLock` component @@ -93,7 +93,7 @@ A component can look like this: A typical test, which asserts that the navigation got prevented, would look like this: ```csharp -var navMan = Services.GetRequiredService(); +var navMan = Services.GetRequiredService(); var cut = RenderComponent(); cut.Find("button").Click(); @@ -123,7 +123,7 @@ As `` navigation is not natively supported in bUnit, the `NavigationMana The test utilizes the `NavigationManager` itself to achieve the same: ```csharp -var navMan = Services.GetRequiredService(); +var navMan = Services.GetRequiredService(); var cut = RenderComponent(); navMan.NavigateTo("/counter"); @@ -149,7 +149,7 @@ NavigationManager.NavigateToLogin("authentication/login", requestOptions); A test could look like this: ```csharp -var navigationManager = Services.GetRequiredService(); +var navigationManager = Services.GetRequiredService(); ActionToTriggerTheNavigationManager(); diff --git a/docs/site/docs/test-doubles/faking-persistentcomponentstate.md b/docs/site/docs/test-doubles/persistentcomponentstate.md similarity index 61% rename from docs/site/docs/test-doubles/faking-persistentcomponentstate.md rename to docs/site/docs/test-doubles/persistentcomponentstate.md index c03f78110..2c8f8ac4b 100644 --- a/docs/site/docs/test-doubles/faking-persistentcomponentstate.md +++ b/docs/site/docs/test-doubles/persistentcomponentstate.md @@ -1,52 +1,52 @@ --- -uid: faking-persistentcomponentstate -title: Faking persistent component state +uid: bunit-persistentcomponentstate +title: Adding persistent component state --- -# Faking persistent component state +# Adding persistent component state -bUnit comes with fake version of the `PersistentComponentState` type in Blazor that makes it possible to test components that use the type. +bUnit comes with its own version of the `PersistentComponentState` type in Blazor that makes it possible to test components that use the type. -## Using the fake `PersistentComponentState` +## Using the `PersistentComponentState` -To use the fake `PersistentComponentState` in bUnit, call the `AddFakePersistentComponentState` extension method on `TestContext`: +To use the `PersistentComponentState` in bUnit, call the `AddBunitPersistentComponentState` extension method on `TestContext`: ```csharp -var fakeState = AddFakePersistentComponentState(); +var state = AddBunitPersistentComponentState(); ``` -Calling `AddFakePersistentComponentState` returns a `FakePersistentComponentState` type, which has three methods; one to persist data, one to get persisted data, and one that triggers any "OnPersisting" callbacks added to the `PersistentComponentState`. +Calling `AddBunitPersistentComponentState` returns a `BunitPersistentComponentState` type, which has three methods; one to persist data, one to get persisted data, and one that triggers any "OnPersisting" callbacks added to the `PersistentComponentState`. To add data to the `PersistentComponentState` before running a test, i.e. to verify that a component uses the persisted state, use the `Persist` method: ```csharp -var fakeState = AddFakePersistentComponentState(); +var state = AddBunitPersistentComponentState(); var key = "STATE KEY"; var data = ...; // data to persist -fakeState.Persist(key, data); +state.Persist(key, data); // render component ``` -To trigger a callback registered with the `PersistentComponentState.RegisterOnPersisting` method, use the `TriggerOnPersisting` method on `FakePersistentComponentState`: +To trigger a callback registered with the `PersistentComponentState.RegisterOnPersisting` method, use the `TriggerOnPersisting` method on `BunitPersistentComponentState`: ```csharp -var fakeState = AddFakePersistentComponentState(); +var state = AddBunitPersistentComponentState(); // render component -fakeState.TriggerOnPersisting(); +state.TriggerOnPersisting(); ``` To check if data has been persisted, use the `TryTake` method: ```csharp -var fakeState = AddFakePersistentComponentState(); +var state = AddBunitPersistentComponentState(); var key = "STATE KEY"; // render component, call TriggerOnPersisting -bool foundState = fakeState.TryTake(key, out var data); +bool foundState = state.TryTake(key, out var data); ``` The following section has a complete example. @@ -91,14 +91,14 @@ In this example, lets test the following `` component that use `Persi } ``` -To test that the `` component uses persisted weather data instead of downloading (generating) it again with the `CreateForecastsAsync` method, use the `Persist` method on the `FakePersistentComponentState` type: +To test that the `` component uses persisted weather data instead of downloading (generating) it again with the `CreateForecastsAsync` method, use the `Persist` method on the `BunitPersistentComponentState` type: ```csharp // Arrange -var fakeState = AddFakePersistentComponentState(); +var state = AddBunitPersistentComponentState(); // Persist a single weather forecast with a temperature of 42 -fakeState.Persist("weather-data", new [] { new WeatherForecast { Temperature = 42 } }); +state.Persist("weather-data", new [] { new WeatherForecast { Temperature = 42 } }); // Act var cut = RenderComponent(); @@ -111,14 +111,14 @@ To test that the `` component correctly persists weather data when it ```csharp // Arrange -var fakeState = AddFakePersistentComponentState(); +var state = AddBunitPersistentComponentState(); var cut = RenderComponent(); // Act - trigger the FetchData components PersistForecasts method -fakeState.TriggerOnPersisting(); +state.TriggerOnPersisting(); // Assert that state was saved and there is a non-empty forecast array returned -var didSaveState = fakeState.TryTake("weather-data", out var savedState); +var didSaveState = state.TryTake("weather-data", out var savedState); Assert.IsTrue(didSaveState); Assert.NotEmpty(savedState); ``` diff --git a/docs/site/docs/toc.md b/docs/site/docs/toc.md index 327afde06..3b6644f46 100644 --- a/docs/site/docs/toc.md +++ b/docs/site/docs/toc.md @@ -23,12 +23,12 @@ # [Test doubles](xref:test-doubles) ## [Emulating IJSRuntime](xref:emulating-ijsruntime) -## [Faking authorization](xref:faking-auth) +## [Adding Authorization](xref:bunit-auth) ## [Mocking HttpClient](xref:mocking-httpclient) ## [Mocking Localizer](xref:mocking-localizer) -## [Faking PersistentComponentState](xref:faking-persistentcomponentstate) -## [Faking NavigationManager](xref:fake-navigation-manager) -## [Faking IWebAssemblyHostEnvironment](xref:fake-webassemblyhostenvironment) +## [Adding PersistentComponentState](xref:bunit-persistentcomponentstate) +## [Adding NavigationManager](xref:bunit-navigation-manager) +## [Adding IWebAssemblyHostEnvironment](xref:bunit-webassemblyhostenvironment) ## [Testing with InputFile component](xref:input-file) # [Extensions](xref:extensions) diff --git a/src/bunit/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/TestServiceProviderExtensions.cs index 40fca7ba0..2041a48ff 100644 --- a/src/bunit/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit/Extensions/TestServiceProviderExtensions.cs @@ -30,19 +30,19 @@ public static IServiceCollection AddDefaultTestContextServices(this IServiceColl services.AddSingleton(); services.AddSingleton(); - // bUnits fake JSInterop + // bUnits JSInterop services.AddSingleton(jsInterop.JSRuntime); - // bUnits fake Navigation Manager - services.AddSingleton(); - services.AddSingleton(s => s.GetRequiredService()); - services.AddSingleton(); + // bUnits Navigation Manager + services.AddSingleton(); + services.AddSingleton(s => s.GetRequiredService()); + services.AddSingleton(); - // bUnits fake WebAssemblyHostEnvironment - services.AddSingleton(); - services.AddSingleton(s => s.GetRequiredService()); + // bUnits WebAssemblyHostEnvironment + services.AddSingleton(); + services.AddSingleton(s => s.GetRequiredService()); - // bUnits fake ScrollToLocationHash + // bUnits ScrollToLocationHash services.AddSingleton(); services.AddSupplyValueFromQueryProvider(); diff --git a/src/bunit/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs b/src/bunit/TestDoubles/Authorization/BunitAuthenticationStateProvider.cs similarity index 90% rename from src/bunit/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs rename to src/bunit/TestDoubles/Authorization/BunitAuthenticationStateProvider.cs index a077f1828..83afac68e 100644 --- a/src/bunit/TestDoubles/Authorization/FakeAuthenticationStateProvider.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthenticationStateProvider.cs @@ -4,22 +4,22 @@ namespace Bunit.TestDoubles; /// -/// Represents a fake implementation of AuthenticationStateProvider for testing purposes that allows +/// Represents a implementation of AuthenticationStateProvider for testing purposes that allows /// user to test components that use authentication and authorization. /// -public class FakeAuthenticationStateProvider : AuthenticationStateProvider +public class BunitAuthenticationStateProvider : AuthenticationStateProvider { private TaskCompletionSource authState = new(); /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// with an initial AuthenticationState. /// /// Identity's user name. /// Roles that this user principal has. /// Claims to add to user principal. /// The authentication type for the user principal. - public FakeAuthenticationStateProvider( + public BunitAuthenticationStateProvider( string userName, IEnumerable? roles = null, IEnumerable? claims = null, @@ -27,9 +27,9 @@ public FakeAuthenticationStateProvider( => SetAuthenticatedState(userName, roles, claims, authenticationType); /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public FakeAuthenticationStateProvider() => SetUnauthenticatedState(); + public BunitAuthenticationStateProvider() => SetUnauthenticatedState(); /// /// Overridden method to get the current authentication state. @@ -114,7 +114,7 @@ private static AuthenticationState CreateAuthenticationState( { roles ??= Array.Empty(); claims ??= Array.Empty(); - authenticationType ??= "bUnit Fake Authentication"; + authenticationType ??= "bUnit Authentication"; var usernameClaim = new Claim(ClaimsIdentity.DefaultNameClaimType, username); var roleClaims = roles.Select(x => new Claim(ClaimsIdentity.DefaultRoleClaimType, x)); diff --git a/src/bunit/TestDoubles/Authorization/FakeAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs similarity index 79% rename from src/bunit/TestDoubles/Authorization/FakeAuthorizationExtensions.cs rename to src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs index ed10641c4..82545ed28 100644 --- a/src/bunit/TestDoubles/Authorization/FakeAuthorizationExtensions.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs @@ -7,21 +7,21 @@ namespace Bunit.TestDoubles; /// Helper methods for registering the Authentication/Authorization services with /// a . /// -public static class FakeAuthorizationExtensions +public static class BunitAuthorizationExtensions { /// /// Adds the appropriate Blazor authentication and authorization services to the to enable /// an authenticated user, as well as adding the component to the /// test contexts render tree. /// - public static TestAuthorizationContext AddTestAuthorization(this TestContextBase context) + public static TestAuthorizationContext AddAuthorization(this TestContextBase context) { ArgumentNullException.ThrowIfNull(context); context.RenderTree.TryAdd(); - context.Services.AddSingleton(); + context.Services.AddSingleton(); #pragma warning disable CS0618 - context.Services.AddSingleton(s => s.GetRequiredService()); + context.Services.AddSingleton(s => s.GetRequiredService()); #pragma warning restore CS0618 var authCtx = new TestAuthorizationContext(); authCtx.SetNotAuthorized(); diff --git a/src/bunit/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationPolicyProvider.cs similarity index 95% rename from src/bunit/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs rename to src/bunit/TestDoubles/Authorization/BunitAuthorizationPolicyProvider.cs index 33d51685f..a20d361c5 100644 --- a/src/bunit/TestDoubles/Authorization/FakeAuthorizationPolicyProvider.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationPolicyProvider.cs @@ -6,7 +6,7 @@ namespace Bunit.TestDoubles; /// Test class that provides an implementation of IAuthorizationPolicyProvider that /// assists user in testing components that use authentication and authorization. ///
    -public class FakeAuthorizationPolicyProvider : IAuthorizationPolicyProvider +public class BunitAuthorizationPolicyProvider : IAuthorizationPolicyProvider { private readonly AuthorizationOptions options = new(); private string policySchemeName = "TestScheme"; diff --git a/src/bunit/TestDoubles/Authorization/FakeAuthorizationService.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationService.cs similarity index 94% rename from src/bunit/TestDoubles/Authorization/FakeAuthorizationService.cs rename to src/bunit/TestDoubles/Authorization/BunitAuthorizationService.cs index 928f697c5..189631880 100644 --- a/src/bunit/TestDoubles/Authorization/FakeAuthorizationService.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationService.cs @@ -10,17 +10,17 @@ namespace Bunit.TestDoubles; /// assists user in testing components by allowing them to set the authorization /// expected authorization response. ///
    -public class FakeAuthorizationService : IAuthorizationService +public class BunitAuthorizationService : IAuthorizationService { private AuthorizationState currentState; private IEnumerable? supportedPolicies; private IEnumerable supportedRoles = Array.Empty(); /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// Initial authorization state. - public FakeAuthorizationService(AuthorizationState state = AuthorizationState.Authorized) + public BunitAuthorizationService(AuthorizationState state = AuthorizationState.Authorized) { currentState = state; } diff --git a/src/bunit/TestDoubles/Authorization/MissingFakeAuthorizationException.cs b/src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs similarity index 62% rename from src/bunit/TestDoubles/Authorization/MissingFakeAuthorizationException.cs rename to src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs index abbeef0b4..3598769f2 100644 --- a/src/bunit/TestDoubles/Authorization/MissingFakeAuthorizationException.cs +++ b/src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs @@ -1,11 +1,11 @@ namespace Bunit.TestDoubles; /// -/// Exception used to indicate that the fake authorization services are required by a test +/// Exception used to indicate that the bunit authorization services are required by a test /// but provided in TestContext.Services. /// [Serializable] -public sealed class MissingFakeAuthorizationException : Exception +public sealed class MissingBunitAuthorizationException : Exception { /// /// Gets the invoking service name. @@ -13,18 +13,18 @@ public sealed class MissingFakeAuthorizationException : Exception public string ServiceName { get; } /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// with the arguments used in the invocation. /// /// The service being used. - public MissingFakeAuthorizationException(string serviceName) + public MissingBunitAuthorizationException(string serviceName) : base($"This test requires {serviceName} to be supplied, because the component under test uses authentication/authorization during the test. You can fix this by calling TestContext.Services.AddAuthorization with appropriate values. More information can be found in the documentation.") { ServiceName = serviceName; - HelpLink = "https://bunit.egilhansen.com/docs/test-doubles/faking-auth"; + HelpLink = "https://bunit.egilhansen.com/docs/test-doubles/bunit-auth"; } - private MissingFakeAuthorizationException(SerializationInfo serializationInfo, StreamingContext streamingContext) + private MissingBunitAuthorizationException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { ServiceName = serializationInfo?.GetString(nameof(ServiceName)) ?? string.Empty; diff --git a/src/bunit/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs b/src/bunit/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs index 74df2cbf7..5a2df061e 100644 --- a/src/bunit/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs +++ b/src/bunit/TestDoubles/Authorization/PlaceholderAuthenticationStateProvider.cs @@ -6,6 +6,6 @@ internal sealed class PlaceholderAuthenticationStateProvider : AuthenticationSta { public override Task GetAuthenticationStateAsync() { - throw new MissingFakeAuthorizationException(nameof(AuthenticationStateProvider)); + throw new MissingBunitAuthorizationException(nameof(AuthenticationStateProvider)); } } diff --git a/src/bunit/TestDoubles/Authorization/PlaceholderAuthorizationService.cs b/src/bunit/TestDoubles/Authorization/PlaceholderAuthorizationService.cs index 527cd1c0e..e112a86fd 100644 --- a/src/bunit/TestDoubles/Authorization/PlaceholderAuthorizationService.cs +++ b/src/bunit/TestDoubles/Authorization/PlaceholderAuthorizationService.cs @@ -7,11 +7,11 @@ internal sealed class PlaceholderAuthorizationService : IAuthorizationService { public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) { - throw new MissingFakeAuthorizationException(nameof(IAuthorizationService)); + throw new MissingBunitAuthorizationException(nameof(IAuthorizationService)); } public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) { - throw new MissingFakeAuthorizationException(nameof(IAuthorizationService)); + throw new MissingBunitAuthorizationException(nameof(IAuthorizationService)); } } diff --git a/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs b/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs index 994fe72e6..4594b8fd0 100644 --- a/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs +++ b/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs @@ -10,9 +10,9 @@ namespace Bunit.TestDoubles; /// public class TestAuthorizationContext { - private readonly FakeAuthorizationService authService = new(); - private readonly FakeAuthorizationPolicyProvider policyProvider = new(); - private readonly FakeAuthenticationStateProvider authProvider = new(); + private readonly BunitAuthorizationService authService = new(); + private readonly BunitAuthorizationPolicyProvider policyProvider = new(); + private readonly BunitAuthenticationStateProvider authProvider = new(); /// /// Gets a value indicating whether user is authenticated. diff --git a/src/bunit/TestDoubles/NavigationInterception/FakeNavigationInterception.cs b/src/bunit/TestDoubles/NavigationInterception/BunitNavigationInterception.cs similarity index 66% rename from src/bunit/TestDoubles/NavigationInterception/FakeNavigationInterception.cs rename to src/bunit/TestDoubles/NavigationInterception/BunitNavigationInterception.cs index 974e5dae0..f6f082bfc 100644 --- a/src/bunit/TestDoubles/NavigationInterception/FakeNavigationInterception.cs +++ b/src/bunit/TestDoubles/NavigationInterception/BunitNavigationInterception.cs @@ -2,7 +2,7 @@ namespace Bunit.TestDoubles; -internal sealed class FakeNavigationInterception : INavigationInterception +internal sealed class BunitNavigationInterception : INavigationInterception { public Task EnableNavigationInterceptionAsync() => Task.CompletedTask; } diff --git a/src/bunit/TestDoubles/NavigationManager/FakeNavigationManager.cs b/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs similarity index 86% rename from src/bunit/TestDoubles/NavigationManager/FakeNavigationManager.cs rename to src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs index e8ccf1190..d4e19e2de 100644 --- a/src/bunit/TestDoubles/NavigationManager/FakeNavigationManager.cs +++ b/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs @@ -1,5 +1,4 @@ using System.Diagnostics; -using Bunit.Rendering; using Microsoft.AspNetCore.Components.Routing; namespace Bunit.TestDoubles; @@ -7,17 +6,17 @@ namespace Bunit.TestDoubles; using URI = Uri; /// -/// Represents a fake that captures calls to +/// Represents a that captures calls to /// for testing purposes. /// [DebuggerDisplay("Current Uri: {Uri}, History Count: {History.Count}")] -public sealed class FakeNavigationManager : NavigationManager +public sealed class BunitNavigationManager : NavigationManager { private readonly TestContextBase testContextBase; private readonly Stack history = new(); /// - /// The navigation history captured by the . + /// The navigation history captured by the . /// This is a stack based collection, so the first element is the latest/current navigation target. /// /// @@ -26,10 +25,10 @@ public sealed class FakeNavigationManager : NavigationManager public IReadOnlyCollection History => history; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - [SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", Justification = "By design. Fake navigation manager defaults to local host as base URI.")] - public FakeNavigationManager(TestContextBase testContextBase) + [SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", Justification = "By design. Bunit navigation manager defaults to local host as base URI.")] + public BunitNavigationManager(TestContextBase testContextBase) { this.testContextBase = testContextBase; Initialize("http://localhost/", "http://localhost/"); diff --git a/src/bunit/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs b/src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs similarity index 67% rename from src/bunit/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs rename to src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs index 8966e14be..66dc01802 100644 --- a/src/bunit/TestDoubles/NavigationManager/FakeSignOutSessionStateManager.cs +++ b/src/bunit/TestDoubles/NavigationManager/BunitSignOutSessionStateManager.cs @@ -3,11 +3,11 @@ namespace Bunit.TestDoubles; /// -/// Represents a fake that captures calls to +/// Represents bUnit's own that captures calls to /// that will help later to assert if the user was logged out /// #pragma warning disable CS0618 -public class FakeSignOutSessionStateManager : SignOutSessionStateManager +public class BunitSignOutSessionStateManager : SignOutSessionStateManager #pragma warning restore CS0618 { /// @@ -16,9 +16,9 @@ public class FakeSignOutSessionStateManager : SignOutSessionStateManager public bool IsSignedOut { get; set; } /// - /// Initializes a new instance of + /// Initializes a new instance of /// - public FakeSignOutSessionStateManager(IJSRuntime jsRuntime) : base(jsRuntime) + public BunitSignOutSessionStateManager(IJSRuntime jsRuntime) : base(jsRuntime) { } diff --git a/src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs similarity index 87% rename from src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs rename to src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs index d10c717b3..c96b29ca6 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentState.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs @@ -5,27 +5,27 @@ namespace Bunit.TestDoubles; /// -/// Represents a fake , that can be used to the +/// Represents a , that can be used to the /// real in the Blazor runtime. /// -public sealed class FakePersistentComponentState +public sealed class BunitPersistentComponentState { private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, }; - private readonly FakePersistentComponentStateStore store; + private readonly BunitPersistentComponentStateStore store; private readonly Lazy manager; private readonly Lazy renderer; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The to pull lazily dependencies from. - internal FakePersistentComponentState(IServiceProvider services) + internal BunitPersistentComponentState(IServiceProvider services) { - store = new FakePersistentComponentStateStore(); + store = new BunitPersistentComponentStateStore(); manager = new Lazy(() => services.GetRequiredService()); renderer = new Lazy(() => services.GetRequiredService().Renderer); } @@ -37,7 +37,7 @@ internal FakePersistentComponentState(IServiceProvider services) /// /// /// Only call this method after all services has been registered with the . - /// Calling this method will lookup dependencies of the + /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// public void TriggerOnPersisting() @@ -51,7 +51,7 @@ public void TriggerOnPersisting() /// /// /// Only call this method after all services has been registered with the . - /// Calling this method will lookup dependencies of the + /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// /// The type. @@ -71,7 +71,7 @@ public void Persist(string key, TValue instance) ///
    /// /// Only call this method after all services has been registered with the . - /// Calling this method will lookup dependencies of the + /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// /// The key used to persist the instance. diff --git a/src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentStateStore.cs similarity index 85% rename from src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs rename to src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentStateStore.cs index 15705494a..385988834 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/FakePersistentComponentStateStore.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentStateStore.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles; -internal class FakePersistentComponentStateStore : IPersistentComponentStateStore +internal class BunitPersistentComponentStateStore : IPersistentComponentStateStore { private readonly Dictionary state = new(StringComparer.Ordinal); diff --git a/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs b/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs index 2ed1e3dbf..adaa05034 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs @@ -3,21 +3,21 @@ namespace Bunit.TestDoubles; /// -/// Extensions related to . +/// Extensions related to . /// public static class TestContextBaseExtensions { /// - /// Adds and returns a to the services of the . + /// Adds and returns a to the services of the . /// - /// The test context to add the to. - /// The added . - public static FakePersistentComponentState AddFakePersistentComponentState(this TestContextBase testContext) + /// The test context to add the to. + /// The added . + public static BunitPersistentComponentState AddBunitPersistentComponentState(this TestContextBase testContext) { ArgumentNullException.ThrowIfNull(testContext); testContext.Services.AddSingleton(); testContext.Services.AddSingleton(s => s.GetRequiredService().State); - return new FakePersistentComponentState(testContext.Services); + return new BunitPersistentComponentState(testContext.Services); } } diff --git a/src/bunit/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs b/src/bunit/TestDoubles/WebAssemblyHostEnvironment/BunitWebAssemblyHostEnvironment.cs similarity index 81% rename from src/bunit/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs rename to src/bunit/TestDoubles/WebAssemblyHostEnvironment/BunitWebAssemblyHostEnvironment.cs index 6cdad1698..aca79cfa9 100644 --- a/src/bunit/TestDoubles/WebAssemblyHostEnvironment/FakeWebAssemblyHostEnvironment.cs +++ b/src/bunit/TestDoubles/WebAssemblyHostEnvironment/BunitWebAssemblyHostEnvironment.cs @@ -3,9 +3,9 @@ namespace Bunit.TestDoubles; /// -/// Represents a fake that makes the and settable. +/// Represents bUnit's own that makes the and settable. /// -public class FakeWebAssemblyHostEnvironment : IWebAssemblyHostEnvironment +public class BunitWebAssemblyHostEnvironment : IWebAssemblyHostEnvironment { /// /// Gets or sets the name of the environment. Default is Production. @@ -40,5 +40,4 @@ public void SetEnvironmentToProduction() { Environment = "Production"; } - } diff --git a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs index caeb410a2..95acc7bff 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs @@ -14,7 +14,7 @@ public AuthorizationTest(ITestOutputHelper outputHelper) public void Test001() { // Arrange - this.AddTestAuthorization(); + this.AddAuthorization(); // Act var cut = RenderComponent(); @@ -27,7 +27,7 @@ public void Test001() public void Test002() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser", AuthorizationState.Authorized); // act @@ -41,7 +41,7 @@ public void Test002() public void Test003() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser", AuthorizationState.Unauthorized); // act @@ -56,7 +56,7 @@ public void Test003() public async Task Test004() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); // start off unauthenticated. var cut = RenderComponent(); @@ -76,7 +76,7 @@ public async Task Test004() public void Test004_Sync() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); // start off unauthenticated. var cut = RenderComponent(); @@ -95,7 +95,7 @@ public void Test004_Sync() public void Test005() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser005", AuthorizationState.Authorized); // start off unauthenticated. @@ -115,18 +115,18 @@ public void Test005() public void Test006() { // act - var ex = Assert.Throws(() => RenderComponent()); + var ex = Assert.Throws(() => RenderComponent()); // assert Assert.Equal("AuthenticationStateProvider", ex.ServiceName); - Assert.Equal("https://bunit.egilhansen.com/docs/test-doubles/faking-auth", ex.HelpLink); + Assert.Equal("https://bunit.egilhansen.com/docs/test-doubles/bunit-auth", ex.HelpLink); } [Fact(DisplayName = "AuthorizeView with set policy with authenticated and authorized user")] public void Test007() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser").SetPolicies("ContentViewer"); // act @@ -140,7 +140,7 @@ public void Test007() public void Test008() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser"); // act @@ -154,7 +154,7 @@ public void Test008() public void Test0081() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser").SetPolicies("OtherPolicy"); // act @@ -168,7 +168,7 @@ public void Test0081() public void Test009() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser").SetRoles("Admin"); // act @@ -182,7 +182,7 @@ public void Test009() public void Test010() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser"); // act @@ -196,7 +196,7 @@ public void Test010() public void Test011() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser").SetRoles("NotAdmin"); // act @@ -210,7 +210,7 @@ public void Test011() public void Test012() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorizing(); // act @@ -225,7 +225,7 @@ public void Test013() { // arrange var userId = new Guid("{5d5fa9c1-abf9-4ed6-8fb0-3365382b629c}"); - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); var emailClaim = new Claim(ClaimTypes.Email, "user@test.com"); var uuidClaim = new Claim(ClaimTypes.Sid, userId.ToString()); authContext.SetAuthorized("TestUser").SetClaims(uuidClaim, emailClaim); @@ -244,7 +244,7 @@ public void Test013() public void Test014() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser"); // act @@ -259,7 +259,7 @@ public void Test014() public void Test020() { var role = "myTestRole"; - var authCtx = this.AddTestAuthorization(); + var authCtx = this.AddAuthorization(); authCtx.SetAuthorized("FooBar"); authCtx.SetRoles(role); @@ -272,7 +272,7 @@ public void Test020() public void Test021() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser"); authContext.SetAuthenticationType("custom-auth-type"); @@ -287,7 +287,7 @@ public void Test021() public void Test022() { // arrange - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("TestUser"); // act diff --git a/tests/bunit.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthenticationStateProviderTest.cs similarity index 85% rename from tests/bunit.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/BunitAuthenticationStateProviderTest.cs index f96ed2e7a..d00400a40 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/FakeAuthenticationStateProviderTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthenticationStateProviderTest.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles.Authorization; -public class FakeAuthenticationStateProviderTest +public class BunitAuthenticationStateProviderTest { [Fact(DisplayName = "Create authenticated AuthenticationState")] public async Task Test001() @@ -9,7 +9,7 @@ public async Task Test001() var roles = new List { "User" }; // act - var authProvider = new FakeAuthenticationStateProvider("TestUser", roles); + var authProvider = new BunitAuthenticationStateProvider("TestUser", roles); var authState = await authProvider.GetAuthenticationStateAsync(); // assert @@ -23,7 +23,7 @@ public async Task Test001() public async Task Test002() { // act - var authProvider = new FakeAuthenticationStateProvider(); + var authProvider = new BunitAuthenticationStateProvider(); var authState = await authProvider.GetAuthenticationStateAsync(); // assert @@ -37,7 +37,7 @@ public async Task Test002() public async Task Test003() { // arrange - var authProvider = new FakeAuthenticationStateProvider(); + var authProvider = new BunitAuthenticationStateProvider(); var stateChangeHandled = false; authProvider.AuthenticationStateChanged += _ => stateChangeHandled = true; diff --git a/tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationPolicyProviderTest.cs similarity index 85% rename from tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationPolicyProviderTest.cs index 25897b285..14608a853 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationPolicyProviderTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationPolicyProviderTest.cs @@ -2,13 +2,13 @@ namespace Bunit.TestDoubles.Authorization; -public class FakeAuthorizationPolicyProviderTest +public class BunitAuthorizationPolicyProviderTest { [Fact(DisplayName = "Get default policy from PolicyProvider.")] public async Task Test001() { // arrange - var provider = new FakeAuthorizationPolicyProvider(); + var provider = new BunitAuthorizationPolicyProvider(); // act var policy = await provider.GetDefaultPolicyAsync(); @@ -24,7 +24,7 @@ public async Task Test001() public async Task Test002() { // arrange - var provider = new FakeAuthorizationPolicyProvider(); + var provider = new BunitAuthorizationPolicyProvider(); // act var policy = await provider.GetFallbackPolicyAsync(); @@ -37,7 +37,7 @@ public async Task Test002() public async Task Test003() { // arrange - var provider = new FakeAuthorizationPolicyProvider(); + var provider = new BunitAuthorizationPolicyProvider(); provider.SetPolicyScheme("TestScheme"); // act @@ -55,7 +55,7 @@ public async Task Test003() public async Task Test004() { // arrange - var provider = new FakeAuthorizationPolicyProvider(); + var provider = new BunitAuthorizationPolicyProvider(); provider.SetPolicyScheme("TestScheme"); // act @@ -73,7 +73,7 @@ public async Task Test004() public void Test006() { // arrange - var provider = new FakeAuthorizationPolicyProvider(); + var provider = new BunitAuthorizationPolicyProvider(); // assert Assert.Throws( diff --git a/tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs similarity index 83% rename from tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs index 92df5a123..fcef20f4e 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/FakeAuthorizationServiceTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs @@ -3,13 +3,13 @@ namespace Bunit.TestDoubles.Authorization; -public class FakeAuthorizationServiceTest +public class BunitAuthorizationServiceTest { [Fact(DisplayName = "Get AuthorizeAsync with an authorized result.")] public async Task Test002() { // arrange - var service = new FakeAuthorizationService(AuthorizationState.Unauthorized); + var service = new BunitAuthorizationService(AuthorizationState.Unauthorized); var user = CreateUserPrincipal("FooBar"); var requirements = new List(); @@ -25,7 +25,7 @@ public async Task Test002() public async Task Test003() { // arrange - var service = new FakeAuthorizationService(); + var service = new BunitAuthorizationService(); var user = CreateUserPrincipal("FooBar"); var requirements = new List(); @@ -41,7 +41,7 @@ public async Task Test003() public async Task Test004() { // arrange - var service = new FakeAuthorizationService(AuthorizationState.Unauthorized); + var service = new BunitAuthorizationService(AuthorizationState.Unauthorized); var user = CreateUserPrincipal("FooBar"); // act @@ -61,7 +61,7 @@ public async Task Test005() var requirements = Array.Empty(); // act - var ex = await Assert.ThrowsAsync(() => + var ex = await Assert.ThrowsAsync(() => authService.AuthorizeAsync(null!, string.Empty, requirements)); // assert @@ -76,7 +76,7 @@ public async Task Test006() var authService = ctx.Services.GetRequiredService(); // act - var ex = await Assert.ThrowsAsync(() => + var ex = await Assert.ThrowsAsync(() => authService.AuthorizeAsync(default!, string.Empty, "testPolicy")); // assert @@ -86,7 +86,7 @@ public async Task Test006() private static ClaimsPrincipal CreateUserPrincipal(string username) { var usernameClaim = new Claim(ClaimsIdentity.DefaultNameClaimType, username); - var identity = new ClaimsIdentity(claims: new[] { usernameClaim }, authenticationType: "bUnit Fake Authentication"); + var identity = new ClaimsIdentity(claims: new[] { usernameClaim }, authenticationType: "bUnit Authentication"); return new ClaimsPrincipal(identity); } } diff --git a/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs b/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs index 74da5968e..63917997d 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs @@ -6,7 +6,7 @@ public class TestAuthorizationContextTest : TestContext public void Test003() { // act - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); // assert Assert.False(authContext.IsAuthenticated); @@ -19,7 +19,7 @@ public void Test003() public void Test0031() { // act - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorizing(); // assert @@ -33,7 +33,7 @@ public void Test0031() public void Test002() { // act - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("DarthPedro", AuthorizationState.Unauthorized); // assert @@ -47,7 +47,7 @@ public void Test002() public void Test0010() { // act - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("DarthPedro"); // assert @@ -61,7 +61,7 @@ public void Test0010() public void Test001() { // act - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("DarthPedro"); authContext.SetRoles("some-role"); @@ -76,7 +76,7 @@ public void Test001() public void Test0011() { // act - var authContext = this.AddTestAuthorization(); + var authContext = this.AddAuthorization(); authContext.SetAuthorized("DarthPedro"); authContext.SetPolicies("TestPolicy", "Other"); diff --git a/tests/bunit.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs similarity index 64% rename from tests/bunit.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs rename to tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs index 8622ea081..865a57bcf 100644 --- a/tests/bunit.tests/TestDoubles/FakeSignOutSessionStateManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs @@ -1,16 +1,16 @@ namespace Bunit.TestDoubles; -public class FakeSignOutSessionStateManagerTest : TestContext +public class BunitSignOutSessionStateManagerTest : TestContext { [Theory, AutoData] public void ShouldSignOut(string randomUserName) { - this.AddTestAuthorization().SetAuthorized(randomUserName); + this.AddAuthorization().SetAuthorized(randomUserName); var cut = RenderComponent(); cut.Find("button").Click(); - Services.GetService()! + Services.GetService()! .IsSignedOut .ShouldBeTrue(); } @@ -18,7 +18,7 @@ public void ShouldSignOut(string randomUserName) [Fact] public async Task ShouldReturnSignOutStateOnValidateSignOutState() { - var cut = new FakeSignOutSessionStateManager(Substitute.For()); + var cut = new BunitSignOutSessionStateManager(Substitute.For()); await cut.SetSignOutState(); var wasValidate = await cut.ValidateSignOutState(); diff --git a/tests/bunit.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs b/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs similarity index 73% rename from tests/bunit.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs rename to tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs index b246aa38f..182023b4f 100644 --- a/tests/bunit.tests/TestDoubles/FakeWebAssemblyHostEnvironmentTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs @@ -1,11 +1,11 @@ namespace Bunit.TestDoubles; -public class FakeWebAssemblyHostEnvironmentTest : TestContext +public class BunitWebAssemblyHostEnvironmentTest : TestContext { [Fact] public void ShouldSayHelloToDevelopers() { - var hostEnvironment = Services.GetRequiredService(); + var hostEnvironment = Services.GetRequiredService(); hostEnvironment.SetEnvironmentToDevelopment(); var cut = RenderComponent(); @@ -17,7 +17,7 @@ public void ShouldSayHelloToDevelopers() [Fact] public void ShouldUseCorrectBaseAddress() { - var hostEnvironment = Services.GetRequiredService(); + var hostEnvironment = Services.GetRequiredService(); hostEnvironment.BaseAddress = "myBaseUrl/"; var cut = RenderComponent(); diff --git a/tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs similarity index 77% rename from tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs rename to tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs index 16553b021..629da5514 100644 --- a/tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationInterceptionTest.cs +++ b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs @@ -1,11 +1,11 @@ namespace Bunit.TestDoubles; -public class FakeNavigationInterceptionTest +public class BunitNavigationInterceptionTest { [Fact(DisplayName = "EnableNavigationInterceptionAsync returns completed task")] public void Test001() { - new FakeNavigationInterception() + new BunitNavigationInterception() .EnableNavigationInterceptionAsync() .IsCompletedSuccessfully .ShouldBeTrue(); @@ -16,6 +16,6 @@ public void Test002() { using var ctx = new TestContext(); ctx.Services.GetService() - .ShouldBeOfType(); + .ShouldBeOfType(); } } diff --git a/tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs similarity index 80% rename from tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs rename to tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs index 2c74eef40..453dcf902 100644 --- a/tests/bunit.tests/TestDoubles/NavigationManager/FakeNavigationManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs @@ -5,26 +5,26 @@ namespace Bunit.TestDoubles; using static Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers; -public class FakeNavigationManagerTest : TestContext +public class BunitNavigationManagerTest : TestContext { - private FakeNavigationManager CreateFakeNavigationManager() - => Services.GetRequiredService(); + private BunitNavigationManager CreateNavigationManager() + => Services.GetRequiredService(); - [Fact(DisplayName = "TestContext.Services has NavigationManager registered by default as FakeNavigationManager")] + [Fact(DisplayName = "TestContext.Services has NavigationManager registered by default as BunitNavigationManager")] public void Test001() { var nm = Services.GetService(); - var fnm = Services.GetService(); + var fnm = Services.GetService(); nm.ShouldNotBeNull(); fnm.ShouldNotBeNull(); nm.ShouldBe(fnm); } - [Fact(DisplayName = "FakeNavigationManager.BaseUrl is set to http://localhost/")] + [Fact(DisplayName = "BunitNavigationManager.BaseUrl is set to http://localhost/")] public void Test002() { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.BaseUri.ShouldBe("http://localhost/"); } @@ -37,7 +37,7 @@ public void Test002() [InlineData("/#åäö")] public void Test003(string uri) { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); var expectedUri = new Uri(new Uri(sut.BaseUri, UriKind.Absolute), new Uri(uri, UriKind.Relative)); sut.NavigateTo(uri); @@ -51,7 +51,7 @@ public void Test003(string uri) [InlineData("http://localhost/foo")] public void Test004(string uri) { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); var expectedUri = new Uri(uri, UriKind.Absolute); sut.NavigateTo(uri); @@ -67,7 +67,7 @@ public void Test005() // arrange LocationChangedEventArgs actualLocationChange = default; var navigationUri = "foo"; - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.LocationChanged += Sut_LocationChanged; // act @@ -87,7 +87,7 @@ void Sut_LocationChanged(object? sender, LocationChangedEventArgs e) [Fact(DisplayName = "LocationChanged is raised on the test renderer's dispatcher")] public void Test006() { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); var cut = RenderComponent(); sut.NavigateTo("foo"); @@ -98,23 +98,23 @@ public void Test006() [Fact(DisplayName = "Uri should not be unescaped")] public void Test007() { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.NavigateTo("/with%20whitespace"); sut.Uri.ShouldEndWith("with%20whitespace"); } - + [Theory(DisplayName = "NavigateTo(uri, forceLoad, replaceHistoryEntry) is saved in history")] [InlineData("/uri", false, false)] [InlineData("/uri", true, false)] [InlineData("/uri", false, true)] public void Test200(string uri, bool forceLoad, bool replaceHistoryEntry) { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.NavigateTo(uri, forceLoad, replaceHistoryEntry); - + var navigationOptions = new NavigationOptions { ForceLoad = forceLoad, ReplaceHistoryEntry = replaceHistoryEntry }; sut.History.ShouldHaveSingleItem() @@ -124,7 +124,7 @@ public void Test200(string uri, bool forceLoad, bool replaceHistoryEntry) [Fact(DisplayName = "NavigateTo with replaceHistoryEntry true replaces previous history entry")] public void Test201() { - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.NavigateTo("/firstUrl"); sut.NavigateTo("/secondUrl", new NavigationOptions { ReplaceHistoryEntry = true }); @@ -141,7 +141,7 @@ public void Test201() public void Test008() { const string externalUri = "https://bunit.dev/docs/getting-started/index.html"; - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.NavigateTo(externalUri); @@ -154,7 +154,7 @@ public void Test009() { var locationChangedInvoked = false; const string externalUri = "https://bunit.dev/docs/getting-started/index.html"; - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.LocationChanged += (s, e) => locationChangedInvoked = true; sut.NavigateTo(externalUri); @@ -162,38 +162,38 @@ public void Test009() locationChangedInvoked.ShouldBeFalse(); } - [Fact(DisplayName = "When component provides NavigationLock, FakeNavigationManager should intercept calls")] + [Fact(DisplayName = "When component provides NavigationLock, BunitNavigationManager should intercept calls")] public void Test010() { - var fakeNavigationManager = CreateFakeNavigationManager(); + var navigationManager = CreateNavigationManager(); var cut = RenderComponent(); cut.Find("button").Click(); cut.Instance.NavigationIntercepted.ShouldBeTrue(); - fakeNavigationManager.History.Single().State.ShouldBe(NavigationState.Prevented); + navigationManager.History.Single().State.ShouldBe(NavigationState.Prevented); } [Fact(DisplayName = "Intercepting external url's should work")] public void Test011() { - var fakeNavigationManager = CreateFakeNavigationManager(); + var navigationManager = CreateNavigationManager(); var cut = RenderComponent(); cut.Find("button").Click(); - fakeNavigationManager.History.ShouldNotBeEmpty(); + navigationManager.History.ShouldNotBeEmpty(); } - [Fact(DisplayName = "Exception while intercepting is set on FakeNaviationManager")] + [Fact(DisplayName = "Exception while intercepting is set on BunitNaviationManager")] public void Test012() { - var fakeNavigationManager = CreateFakeNavigationManager(); + var navigationManager = CreateNavigationManager(); var cut = RenderComponent(); cut.Find("button").Click(); - var entry = fakeNavigationManager.History.Single(); + var entry = navigationManager.History.Single(); entry.Exception.ShouldBeOfType(); entry.State.ShouldBe(NavigationState.Faulted); } @@ -201,16 +201,16 @@ public void Test012() [Fact(DisplayName = "StateFromJson deserialize InteractiveRequestOptions")] public void Test013() { - var fakeNavigationManager = CreateFakeNavigationManager(); + var navigationManager = CreateNavigationManager(); var requestOptions = new InteractiveRequestOptions { ReturnUrl = "return", Interaction = InteractionType.SignIn, }; requestOptions.TryAddAdditionalParameter("library", "bunit"); - fakeNavigationManager.NavigateToLogin("/some-url", requestOptions); + navigationManager.NavigateToLogin("/some-url", requestOptions); - var options = fakeNavigationManager.History.Last().StateFromJson(); + var options = navigationManager.History.Last().StateFromJson(); options.ShouldNotBeNull(); options.Interaction.ShouldBe(InteractionType.SignIn); options.ReturnUrl.ShouldBe("return"); @@ -221,40 +221,40 @@ public void Test013() [Fact(DisplayName = "Given no content in state then StateFromJson throws")] public void Test014() { - var fakeNavigationManager = CreateFakeNavigationManager(); - fakeNavigationManager.NavigateTo("/some-url"); + var navigationManager = CreateNavigationManager(); + navigationManager.NavigateTo("/some-url"); Should.Throw( - () => fakeNavigationManager.History.Last().StateFromJson()); + () => navigationManager.History.Last().StateFromJson()); } [Fact(DisplayName = "StateFromJson with invalid json throws")] public void Test015() { - var fakeNavigationManager = CreateFakeNavigationManager(); + var navigationManager = CreateNavigationManager(); - fakeNavigationManager.NavigateTo("/login", new NavigationOptions { HistoryEntryState = "" }); + navigationManager.NavigateTo("/login", new NavigationOptions { HistoryEntryState = "" }); Should.Throw( - () => fakeNavigationManager.History.Last().StateFromJson()); + () => navigationManager.History.Last().StateFromJson()); } - + [Fact(DisplayName = "Navigate to url with state should set that state on the NavigationManager")] public void Test016() { const string State = "State"; - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.NavigateTo("/internal", new NavigationOptions { HistoryEntryState = State }); sut.HistoryEntryState.ShouldBe(State); } - + [Fact(DisplayName = "Navigate to url with force reload resets state")] public void Test017() { const string State = "State"; - var sut = CreateFakeNavigationManager(); + var sut = CreateNavigationManager(); sut.NavigateTo("/internal", new NavigationOptions { HistoryEntryState = State }); sut.NavigateTo("/internal", new NavigationOptions { HistoryEntryState = State, ForceLoad = true}); diff --git a/tests/bunit.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs b/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs similarity index 58% rename from tests/bunit.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs rename to tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs index dc45b2c52..306760a11 100644 --- a/tests/bunit.tests/TestDoubles/PersistentComponentState/FakePersistentComponentStateTest.cs +++ b/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs @@ -1,26 +1,26 @@ namespace Bunit.TestDoubles; -public class FakePersistentComponentStateTest : TestContext +public class BunitPersistentComponentStateTest : TestContext { - public FakePersistentComponentStateTest(ITestOutputHelper outputHelper) + public BunitPersistentComponentStateTest(ITestOutputHelper outputHelper) { Services.AddXunitLogger(outputHelper); } - [Fact(DisplayName = "AddFakePersistentComponentState is registers PersistentComponentState in services")] + [Fact(DisplayName = "AddBunitPersistentComponentState is registers PersistentComponentState in services")] public void Test001() { - _ = this.AddFakePersistentComponentState(); + _ = this.AddBunitPersistentComponentState(); var actual = Services.GetService(); actual.ShouldNotBeNull(); } - [Fact(DisplayName = "AddFakePersistentComponentState enables PersistentComponentState injection into components")] + [Fact(DisplayName = "AddBunitPersistentComponentState enables PersistentComponentState injection into components")] public void Test002() { - this.AddFakePersistentComponentState(); + this.AddBunitPersistentComponentState(); var cut = RenderComponent(); @@ -31,9 +31,9 @@ public void Test002() [AutoData] public void Test011(string key, string data) { - var fakeState = this.AddFakePersistentComponentState(); + var state = this.AddBunitPersistentComponentState(); - fakeState.Persist(key, data); + state.Persist(key, data); var store = Services.GetService(); store.TryTakeFromJson(key, out var actual).ShouldBeTrue(); @@ -43,12 +43,12 @@ public void Test011(string key, string data) [Fact(DisplayName = "TryTake returns true if key contains data saved in store")] public void Test012() { - var fakeState = this.AddFakePersistentComponentState(); + var state = this.AddBunitPersistentComponentState(); var cut = RenderComponent(); - fakeState.TriggerOnPersisting(); + state.TriggerOnPersisting(); - fakeState.TryTake(PersistentComponentStateSample.PersistenceKey, out var actual).ShouldBeTrue(); + state.TryTake(PersistentComponentStateSample.PersistenceKey, out var actual).ShouldBeTrue(); actual.ShouldBeEquivalentTo(cut.Instance.Forecasts); } @@ -56,16 +56,16 @@ public void Test012() [AutoData] public void Test013(string key) { - var fakeState = this.AddFakePersistentComponentState(); + var state = this.AddBunitPersistentComponentState(); - fakeState.TryTake(key, out var actual).ShouldBeFalse(); + state.TryTake(key, out _).ShouldBeFalse(); } [Fact(DisplayName = "TriggerOnPersisting triggers OnPersisting callbacks added to store")] public void Test014() { var onPersistingCalledTimes = 0; - var fakeState = this.AddFakePersistentComponentState(); + var state = this.AddBunitPersistentComponentState(); var store = Services.GetService(); store.RegisterOnPersisting(() => { @@ -73,7 +73,7 @@ public void Test014() return Task.CompletedTask; }); - fakeState.TriggerOnPersisting(); + state.TriggerOnPersisting(); onPersistingCalledTimes.ShouldBe(1); } From 580eca641de08582a8a50e5d81a5b1dcd4e71bee Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 11:11:12 +0100 Subject: [PATCH 009/100] refactor: Merge TestContext with TestContextBase --- MIGRATION.md | 3 + .../CustomServiceProviderFactoryUsage.cs | 12 +- .../docs/interaction/dispose-components.md | 4 +- .../docs/providing-input/root-render-tree.md | 2 +- docs/site/docs/test-doubles/auth.md | 4 +- .../InstanceComponentFactory{TComponent}.cs | 2 +- .../Internal/AngleSharpExtensions.cs | 6 +- .../RenderedComponentRenderExtensions.cs | 2 +- .../Extensions/RenderedFragmentExtensions.cs | 4 +- .../RenderedFragmentInvokeAsyncExtensions.cs | 8 +- ...ions.cs => TestContextRenderExtensions.cs} | 12 +- .../TestServiceProviderExtensions.cs | 2 +- .../WaitForHelpers/WaitForHelper.cs | 4 +- .../Rendering/BunitComponentActivator.cs | 2 +- src/bunit/Rendering/BunitHtmlParser.cs | 2 +- src/bunit/TestContext.cs | 99 +++++++- src/bunit/TestContextBase.cs | 117 --------- .../BunitAuthorizationExtensions.cs | 2 +- .../BunitNavigationManager.cs | 8 +- .../BunitPersistentComponentState.cs | 8 +- ...Extensions.cs => TestContextExtensions.cs} | 4 +- tests/bunit.tests/TestContextBaseTest.cs | 61 ----- tests/bunit.tests/TestContextBaseTest.net5.cs | 173 ------------- tests/bunit.tests/TestContextTest.cs | 230 ++++++++++++++++++ tests/bunit.tests/TestContextTest.net6.cs | 11 - 25 files changed, 373 insertions(+), 409 deletions(-) rename src/bunit/Extensions/{TestContextBaseRenderExtensions.cs => TestContextRenderExtensions.cs} (82%) delete mode 100644 src/bunit/TestContextBase.cs rename src/bunit/TestDoubles/PersistentComponentState/{TestContextBaseExtensions.cs => TestContextExtensions.cs} (90%) delete mode 100644 tests/bunit.tests/TestContextBaseTest.cs delete mode 100644 tests/bunit.tests/TestContextBaseTest.net5.cs delete mode 100644 tests/bunit.tests/TestContextTest.net6.cs diff --git a/MIGRATION.md b/MIGRATION.md index cbafd337b..675181a74 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -39,3 +39,6 @@ The `Fake` prefix has been replaced with `Bunit` in many test doubles. For examp ### Renamed `AddTestAuthorization` to `AddAuthorization` The `AddTestAuthorization` method on `TestContext` has been renamed to `AddAuthorization`. If you used `AddTestAuthorization`, you should replace it with `AddAuthorization`. + +## Merged `TestContext` and `TestContextBase` +The `TestContext` and `TestContextBase` classes have been merged into a single `TestContext` class. All references to `TestContextBase` should replace them with `TestContext` to migrate. diff --git a/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs b/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs index df4e5800d..cee28d37a 100644 --- a/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs +++ b/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs @@ -49,10 +49,10 @@ void ConfigureContainer(ContainerBuilder containerBuilder) //get a service which was installed in the bUnit ServiceCollection - var testContextBase = Services.GetService(); + var testContext = Services.GetService(); - Assert.NotNull(testContextBase); - Assert.Equal(this, testContextBase); + Assert.NotNull(testContext); + Assert.Equal(this, testContext); } [Fact] @@ -81,9 +81,9 @@ ILifetimeScope ConfigureContainer(IServiceCollection services) //get a service which was installed in the bUnit ServiceCollection - var testContextBase = Services.GetService(); + var testContext = Services.GetService(); - Assert.NotNull(testContextBase); - Assert.Equal(this, testContextBase); + Assert.NotNull(testContext); + Assert.Equal(this, testContext); } } diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index 8995d9e94..b996b67a7 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -4,7 +4,7 @@ title: Disposing components and their children --- # Disposing components -To dispose all components rendered with a `TestContext`, use the [`DisposeComponents`](xref:Bunit.TestContextBase.DisposeComponents) method. Calling this method will dispose all rendered components, calling any `IDisposable.Dispose` or/and `IAsyncDisposable.DisposeAsync` methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components. +To dispose all components rendered with a `TestContext`, use the [`DisposeComponents`](xref:Bunit.TestContext.DisposeComponents) method. Calling this method will dispose all rendered components, calling any `IDisposable.Dispose` or/and `IAsyncDisposable.DisposeAsync` methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components. Disposing rendered components enables testing of logic in `Dispose` methods, e.g., event handlers, that should be detached to avoid memory leaks. @@ -16,7 +16,7 @@ The following example of this: > For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Checking for exceptions -`Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.TestContextBase.DisposeComponents) will throw the exception to the user code: +`Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.TestContext.DisposeComponents) will throw the exception to the user code: [!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L28-L32)] diff --git a/docs/site/docs/providing-input/root-render-tree.md b/docs/site/docs/providing-input/root-render-tree.md index 898ec414e..cbc652f2d 100644 --- a/docs/site/docs/providing-input/root-render-tree.md +++ b/docs/site/docs/providing-input/root-render-tree.md @@ -7,7 +7,7 @@ title: Controlling the root render tree The root render tree, the render tree in which components under test are rendered, can be added to before components are rendered with bUnit's test context. This is mostly useful when a component under test, or a component it depends on, must be rendered inside another component, that provides a cascading value to it. -For example, when using Blazor’s authentication, it is common to add the `CascadingAuthenticationState` component higher up the render tree, such that it can provide authentication state to those components below it that need it. Adding this through the property on the type makes it possible to add it once in a shared setup method, and not have to do so in every test method during the call to [`RenderComponent()`](xref:Bunit.Rendering.RootRenderTree.Add``1(System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})). +For example, when using Blazor’s authentication, it is common to add the `CascadingAuthenticationState` component higher up the render tree, such that it can provide authentication state to those components below it that need it. Adding this through the property on the type makes it possible to add it once in a shared setup method, and not have to do so in every test method during the call to [`RenderComponent()`](xref:Bunit.Rendering.RootRenderTree.Add``1(System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})). This can also be useful when writing tests that use a third-party component library, that require a special root component to be added to the render tree, but which otherwise don’t change between tests. diff --git a/docs/site/docs/test-doubles/auth.md b/docs/site/docs/test-doubles/auth.md index 8a94cb728..3decf8909 100644 --- a/docs/site/docs/test-doubles/auth.md +++ b/docs/site/docs/test-doubles/auth.md @@ -15,10 +15,10 @@ The test implementation of Blazor's authentication and authorization can be put - **Authenticated** and **authorized** - **Authenticated** and **authorized** with one or more **roles**, **claims**, and/or **policies** -bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContextBase)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. +bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContext)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. > [!NOTE] -> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContextBase)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `this.AddAuthorization()`. +> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContext)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `this.AddAuthorization()`. The following sections show how to set each of these states in a test. diff --git a/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs b/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs index 0ce047387..3e3ebe461 100644 --- a/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs +++ b/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs @@ -18,7 +18,7 @@ public IComponent Create(Type componentType) { throw new InvalidOperationException( $"The instance object passed to the" + - $"{nameof(TestContextBase.ComponentFactories)}.{nameof(ComponentFactoryCollectionExtensions.Add)}<{typeof(TComponent).Name}>(instance) method can only be used to replace " + + $"{nameof(TestContext.ComponentFactories)}.{nameof(ComponentFactoryCollectionExtensions.Add)}<{typeof(TComponent).Name}>(instance) method can only be used to replace " + $"one {typeof(TComponent)} component in the render tree."); } diff --git a/src/bunit/Extensions/Internal/AngleSharpExtensions.cs b/src/bunit/Extensions/Internal/AngleSharpExtensions.cs index e8497a09b..a98d1830a 100644 --- a/src/bunit/Extensions/Internal/AngleSharpExtensions.cs +++ b/src/bunit/Extensions/Internal/AngleSharpExtensions.cs @@ -65,9 +65,9 @@ public static HtmlComparer GetHtmlComparer(this INodeList nodes) /// owning context, if one is available. /// /// The or null if not found. - public static TestContextBase? GetTestContext(this INode? node) + public static TestContext? GetTestContext(this INode? node) { - return node?.Owner?.Context.GetService(); + return node?.Owner?.Context.GetService(); } /// @@ -75,7 +75,7 @@ public static HtmlComparer GetHtmlComparer(this INodeList nodes) /// owning context, if one is available. /// /// The or null if not found. - public static TestContextBase? GetTestContext(this INodeList nodes) + public static TestContext? GetTestContext(this INodeList nodes) { return nodes?.Length > 0 ? nodes[0].GetTestContext() : null; } diff --git a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs index a210d137f..a25be08e3 100644 --- a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs @@ -28,7 +28,7 @@ public static void SetParametersAndRender(this IRenderedComponent().Renderer; + var renderer = (TestRenderer)renderedComponent.Services.GetRequiredService().Renderer; try { diff --git a/src/bunit/Extensions/RenderedFragmentExtensions.cs b/src/bunit/Extensions/RenderedFragmentExtensions.cs index 236b90bb2..83732d052 100644 --- a/src/bunit/Extensions/RenderedFragmentExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentExtensions.cs @@ -55,7 +55,7 @@ public static IRenderedComponent FindComponent(this IRen { ArgumentNullException.ThrowIfNull(renderedFragment); - var renderer = renderedFragment.Services.GetRequiredService().Renderer; + var renderer = renderedFragment.Services.GetRequiredService().Renderer; return renderer.FindComponent(renderedFragment); } @@ -70,7 +70,7 @@ public static IReadOnlyList> FindComponents().Renderer; + var renderer = renderedFragment.Services.GetRequiredService().Renderer; var components = renderer.FindComponents(renderedFragment); return components.OfType>().ToArray(); diff --git a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index c95505202..974a99dd4 100644 --- a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -19,7 +19,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Action w return renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); @@ -37,7 +37,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); @@ -55,7 +55,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Fu return renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); @@ -73,7 +73,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Fu return renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); diff --git a/src/bunit/Extensions/TestContextBaseRenderExtensions.cs b/src/bunit/Extensions/TestContextRenderExtensions.cs similarity index 82% rename from src/bunit/Extensions/TestContextBaseRenderExtensions.cs rename to src/bunit/Extensions/TestContextRenderExtensions.cs index 88126a3c2..cd11843fa 100644 --- a/src/bunit/Extensions/TestContextBaseRenderExtensions.cs +++ b/src/bunit/Extensions/TestContextRenderExtensions.cs @@ -3,18 +3,18 @@ namespace Bunit.Extensions; /// -/// Extensions methods for types. +/// Extensions methods for types. /// -public static class TestContextBaseRenderExtensions +public static class TestContextRenderExtensions { /// - /// Renders a component, declared in the , inside the . + /// Renders a component, declared in the , inside the . /// /// The type of component to render. /// Test context to use to render with. /// The that contains a declaration of the component. /// A . - public static IRenderedComponent RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) + public static IRenderedComponent RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(testContext); @@ -24,12 +24,12 @@ public static IRenderedComponent RenderInsideRenderTree( } /// - /// Renders a fragment, declared in the , inside the . + /// Renders a fragment, declared in the , inside the . /// /// Test context to use to render with. /// The to render. /// A . - public static IRenderedFragment RenderInsideRenderTree(this TestContextBase testContext, RenderFragment renderFragment) + public static IRenderedFragment RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) { ArgumentNullException.ThrowIfNull(testContext); diff --git a/src/bunit/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/TestServiceProviderExtensions.cs index 2041a48ff..ce42faeff 100644 --- a/src/bunit/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit/Extensions/TestServiceProviderExtensions.cs @@ -17,7 +17,7 @@ public static class TestServiceProviderExtensions /// /// Registers the default services required by the web . /// - public static IServiceCollection AddDefaultTestContextServices(this IServiceCollection services, TestContextBase testContext, BunitJSInterop jsInterop) + public static IServiceCollection AddDefaultTestContextServices(this IServiceCollection services, TestContext testContext, BunitJSInterop jsInterop) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(testContext); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index 6e26324a6..6408dcf5b 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -56,7 +56,7 @@ protected WaitForHelper( logger = renderedFragment.Services.CreateLogger>(); renderer = (TestRenderer)renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer; checkPassedCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); timer = new Timer(_ => @@ -198,6 +198,6 @@ private static TimeSpan GetRuntimeTimeout(TimeSpan? timeout) { return Debugger.IsAttached ? Timeout.InfiniteTimeSpan - : timeout ?? TestContextBase.DefaultWaitTimeout; + : timeout ?? TestContext.DefaultWaitTimeout; } } diff --git a/src/bunit/Rendering/BunitComponentActivator.cs b/src/bunit/Rendering/BunitComponentActivator.cs index 400d94877..426b4da24 100644 --- a/src/bunit/Rendering/BunitComponentActivator.cs +++ b/src/bunit/Rendering/BunitComponentActivator.cs @@ -19,7 +19,7 @@ public IComponent CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessed } // The FragmentContainer is a bUnit component added to the - // render tree to separate the components from the TestContextBase.RenderTree + // render tree to separate the components from the TestContext.RenderTree // and the components in the render fragment being rendered. // It should never be replaced by another component, as // this would break bUnits ability to detect the start diff --git a/src/bunit/Rendering/BunitHtmlParser.cs b/src/bunit/Rendering/BunitHtmlParser.cs index 0551f71c8..c44abab7f 100644 --- a/src/bunit/Rendering/BunitHtmlParser.cs +++ b/src/bunit/Rendering/BunitHtmlParser.cs @@ -34,7 +34,7 @@ public BunitHtmlParser() /// Initializes a new instance of the class /// with a AngleSharp context registered. /// - public BunitHtmlParser(HtmlComparer htmlComparer, TestContextBase testContext) + public BunitHtmlParser(HtmlComparer htmlComparer, TestContext testContext) : this(Configuration.Default.WithCss() .With(htmlComparer ?? throw new ArgumentNullException(nameof(htmlComparer))) .With(testContext ?? throw new ArgumentNullException(nameof(testContext))) diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index afcb45ff9..de3286aa6 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -7,22 +7,116 @@ namespace Bunit; /// /// A test context is a factory that makes it possible to create components under tests. /// -public class TestContext : TestContextBase +public class TestContext : IDisposable { + private bool disposed; + private ITestRenderer? testRenderer; + + /// + /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . + /// + /// The default is 1 second. + public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); + + /// + /// Gets the renderer used by the test context. + /// + public ITestRenderer Renderer => testRenderer ??= CreateTestRenderer(); + /// /// Gets bUnits JSInterop, that allows setting up handlers for invocations /// that components under tests will issue during testing. It also makes it possible to verify that the invocations has happened as expected. /// public BunitJSInterop JSInterop { get; } = new BunitJSInterop(); + /// + /// Gets the service collection and service provider that is used when a + /// component is rendered by the test context. + /// + public TestServiceProvider Services { get; } + + /// + /// Gets the that all components rendered with the + /// RenderComponent<TComponent>() methods, are rendered inside. + /// + /// + /// Use this to add default layout- or root-components which a component under test + /// should be rendered under. + /// + public RootRenderTree RenderTree { get; } = new(); + + /// + /// Gets the . Factories added to it + /// will be used to create components during testing, starting with the last added + /// factory. If no factories in the collection can create a requested component, + /// then the default Blazor factory is used. + /// + public ComponentFactoryCollection ComponentFactories { get; } = new(); + /// /// Initializes a new instance of the class. /// public TestContext() { + Services = new TestServiceProvider(); + Services.AddSingleton(_ => ComponentFactories); Services.AddDefaultTestContextServices(this, JSInterop); } + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Disposes of the test context resources, in particular it disposes the + /// service provider. Any async services registered with the service provider will disposed first, + /// but their disposal will not be awaited.. + /// + /// + /// The disposing parameter should be false when called from a finalizer, and true when called from the + /// method. In other words, it is true when deterministically called and false when non-deterministically called. + /// + /// Set to true if called from , false if called from a finalizer.f. + [SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly", Justification = "Explicitly ignoring DisposeAsync to avoid breaking changes to API surface.")] + protected virtual void Dispose(bool disposing) + { + if (disposed || !disposing) + return; + + disposed = true; + + // Ensure the renderer is disposed before all others, + // otherwise a render cycle may be ongoing and try to access + // the service provider to perform operations. + if (testRenderer is IDisposable renderer) + { + renderer.Dispose(); + } + + // Ignore the async task as GetAwaiter().GetResult() can cause deadlock + // and implementing IAsyncDisposable in TestContext will be a breaking change. + // + // NOTE: This has to be called before Services.Dispose(). + // If there are IAsyncDisposable services registered, calling Dispose first + // causes the service provider to throw an exception. + _ = Services.DisposeAsync(); + + // The service provider should dispose of any + // disposable object it has created, when it is disposed. + Services.Dispose(); + } + + /// + /// Disposes all components rendered via this . + /// + public void DisposeComponents() + { + Renderer.DisposeComponents(); + } + /// /// Instantiates and performs a first render of a component of type . /// @@ -81,8 +175,7 @@ public virtual IRenderedFragment Render(RenderFragment renderFragment) /// protected virtual void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { } - /// - protected override ITestRenderer CreateTestRenderer() + private TestRenderer CreateTestRenderer() { var renderedComponentActivator = Services.GetRequiredService(); var logger = Services.GetRequiredService(); diff --git a/src/bunit/TestContextBase.cs b/src/bunit/TestContextBase.cs deleted file mode 100644 index 95e999590..000000000 --- a/src/bunit/TestContextBase.cs +++ /dev/null @@ -1,117 +0,0 @@ -using Bunit.Rendering; - -namespace Bunit; - -/// -/// A test context is a factory that makes it possible to create components under tests. -/// -public abstract class TestContextBase : IDisposable -{ - private bool disposed; - private ITestRenderer? testRenderer; - - /// - /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . - /// - /// The default is 1 second. - public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); - - /// - /// Gets the renderer used by the test context. - /// - public ITestRenderer Renderer => testRenderer ??= CreateTestRenderer(); - - /// - /// Creates the renderer. - /// - protected abstract ITestRenderer CreateTestRenderer(); - - /// - /// Gets the service collection and service provider that is used when a - /// component is rendered by the test context. - /// - public TestServiceProvider Services { get; } - - /// - /// Gets the that all components rendered with the - /// RenderComponent<TComponent>() methods, are rendered inside. - /// - /// - /// Use this to add default layout- or root-components which a component under test - /// should be rendered under. - /// - public RootRenderTree RenderTree { get; } = new(); - - /// - /// Gets the . Factories added to it - /// will be used to create components during testing, starting with the last added - /// factory. If no factories in the collection can create a requested component, - /// then the default Blazor factory is used. - /// - public ComponentFactoryCollection ComponentFactories { get; } = new(); - - /// - /// Initializes a new instance of the class. - /// - protected TestContextBase() - { - Services = new TestServiceProvider(); - Services.AddSingleton(_ => ComponentFactories); - } - - /// - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes of the test context resources, in particular it disposes the - /// service provider. Any async services registered with the service provider will disposed first, - /// but their disposal will not be awaited.. - /// - /// - /// The disposing parameter should be false when called from a finalizer, and true when called from the - /// method. In other words, it is true when deterministically called and false when non-deterministically called. - /// - /// Set to true if called from , false if called from a finalizer.f. - [SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly", Justification = "Explicitly ignoring DisposeAsync to avoid breaking changes to API surface.")] - protected virtual void Dispose(bool disposing) - { - if (disposed || !disposing) - return; - - disposed = true; - - // Ensure the renderer is disposed before all others, - // otherwise a render cycle may be ongoing and try to access - // the service provider to perform operations. - if (testRenderer is IDisposable renderer) - { - renderer.Dispose(); - } - - // Ignore the async task as GetAwaiter().GetResult() can cause deadlock - // and implementing IAsyncDisposable in TestContext will be a breaking change. - // - // NOTE: This has to be called before Services.Dispose(). - // If there are IAsyncDisposable services registered, calling Dispose first - // causes the service provider to throw an exception. - _ = Services.DisposeAsync(); - - // The service provider should dispose of any - // disposable object it has created, when it is disposed. -#pragma warning disable S3966 // On purpose to dispose synchronously and asynchronously - Services.Dispose(); -#pragma warning restore S3966 - } - - /// - /// Disposes all components rendered via this . - /// - public void DisposeComponents() - { - Renderer.DisposeComponents(); - } -} diff --git a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs index 82545ed28..dbd62c071 100644 --- a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs @@ -14,7 +14,7 @@ public static class BunitAuthorizationExtensions /// an authenticated user, as well as adding the component to the /// test contexts render tree. /// - public static TestAuthorizationContext AddAuthorization(this TestContextBase context) + public static TestAuthorizationContext AddAuthorization(this TestContext context) { ArgumentNullException.ThrowIfNull(context); diff --git a/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs b/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs index d4e19e2de..171c51f62 100644 --- a/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs +++ b/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs @@ -12,7 +12,7 @@ namespace Bunit.TestDoubles; [DebuggerDisplay("Current Uri: {Uri}, History Count: {History.Count}")] public sealed class BunitNavigationManager : NavigationManager { - private readonly TestContextBase testContextBase; + private readonly TestContext testContext; private readonly Stack history = new(); /// @@ -28,9 +28,9 @@ public sealed class BunitNavigationManager : NavigationManager /// Initializes a new instance of the class. /// [SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", Justification = "By design. Bunit navigation manager defaults to local host as base URI.")] - public BunitNavigationManager(TestContextBase testContextBase) + public BunitNavigationManager(TestContext testContext) { - this.testContextBase = testContextBase; + this.testContext = testContext; Initialize("http://localhost/", "http://localhost/"); } @@ -51,7 +51,7 @@ protected override void NavigateToCore(string uri, NavigationOptions options) history.Pop(); HistoryEntryState = options.ForceLoad ? null : options.HistoryEntryState; - testContextBase.Renderer.Dispatcher.InvokeAsync(async () => + testContext.Renderer.Dispatcher.InvokeAsync(async () => { Uri = absoluteUri.OriginalString; diff --git a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs index c96b29ca6..d6ae10f98 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs @@ -27,7 +27,7 @@ internal BunitPersistentComponentState(IServiceProvider services) { store = new BunitPersistentComponentStateStore(); manager = new Lazy(() => services.GetRequiredService()); - renderer = new Lazy(() => services.GetRequiredService().Renderer); + renderer = new Lazy(() => services.GetRequiredService().Renderer); } /// @@ -36,7 +36,7 @@ internal BunitPersistentComponentState(IServiceProvider services) /// component persistence. /// /// - /// Only call this method after all services has been registered with the . + /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// @@ -50,7 +50,7 @@ public void TriggerOnPersisting() /// Persists under the given in the store. /// /// - /// Only call this method after all services has been registered with the . + /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// @@ -70,7 +70,7 @@ public void Persist(string key, TValue instance) /// When the key is present, the state is successfully returned via . /// /// - /// Only call this method after all services has been registered with the . + /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// diff --git a/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs b/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs similarity index 90% rename from src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs rename to src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs index adaa05034..f0d3b655c 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/TestContextBaseExtensions.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs @@ -5,14 +5,14 @@ namespace Bunit.TestDoubles; /// /// Extensions related to . /// -public static class TestContextBaseExtensions +public static class TestContextExtensions { /// /// Adds and returns a to the services of the . /// /// The test context to add the to. /// The added . - public static BunitPersistentComponentState AddBunitPersistentComponentState(this TestContextBase testContext) + public static BunitPersistentComponentState AddBunitPersistentComponentState(this TestContext testContext) { ArgumentNullException.ThrowIfNull(testContext); diff --git a/tests/bunit.tests/TestContextBaseTest.cs b/tests/bunit.tests/TestContextBaseTest.cs deleted file mode 100644 index e82ddbec8..000000000 --- a/tests/bunit.tests/TestContextBaseTest.cs +++ /dev/null @@ -1,61 +0,0 @@ -using Bunit.TestAssets.SampleComponents.DisposeComponents; - -namespace Bunit; - -public partial class TestContextBaseTest : TestContext -{ - [Fact(DisplayName = "DisposeComponents disposes rendered components in parent to child order")] - public void Test101() - { - var callStack = new List(); - RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); - - DisposeComponents(); - - callStack.Count.ShouldBe(2); - callStack[0].ShouldBe("ParentDispose"); - callStack[1].ShouldBe("ChildDispose"); - } - - [Fact(DisplayName = "DisposeComponents disposes multiple rendered components")] - public void Test102() - { - var callStack = new List(); - RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); - RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); - - DisposeComponents(); - - callStack.Count.ShouldBe(2); - } - - [Fact(DisplayName = "DisposeComponents rethrows exceptions from Dispose methods in components")] - public void Test103() - { - RenderComponent(); - var action = () => DisposeComponents(); - - action.ShouldThrow(); - } - - [Fact(DisplayName = "DisposeComponents disposes components nested in render fragments")] - public void Test104() - { - var callStack = new List(); - Render(DisposeFragments.ChildDisposeAsFragment(callStack)); - - DisposeComponents(); - - callStack.Count.ShouldBe(1); - } - - private sealed class ThrowExceptionComponent : ComponentBase, IDisposable - { - public void Dispose() - { -#pragma warning disable S3877 - throw new NotSupportedException(); -#pragma warning restore S3877 - } - } -} diff --git a/tests/bunit.tests/TestContextBaseTest.net5.cs b/tests/bunit.tests/TestContextBaseTest.net5.cs deleted file mode 100644 index 09af8e57a..000000000 --- a/tests/bunit.tests/TestContextBaseTest.net5.cs +++ /dev/null @@ -1,173 +0,0 @@ -using Bunit.TestAssets.SampleComponents.DisposeComponents; - -namespace Bunit; - -public partial class TestContextBaseTest : TestContext -{ - [Fact(DisplayName = "ComponentFactories CanCreate() method are checked during component instantiation")] - public void Test0001() - { - var mock = CreateMockComponentFactory(canCreate: _ => false, create: _ => null); - ComponentFactories.Add(mock); - - RenderComponent(); - - mock.Received(1).CanCreate(typeof(Simple1)); - mock.DidNotReceive().Create(Arg.Any()); - } - - [Fact(DisplayName = "ComponentFactories Create() method is called when their CanCreate() method returns true")] - public void Test0002() - { - var mock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); - ComponentFactories.Add(mock); - - RenderComponent(); - - mock.Received(1).CanCreate(typeof(Simple1)); - mock.Received(1).Create(typeof(Simple1)); - } - - [Fact(DisplayName = "ComponentFactories is used in last added order")] - public void Test0003() - { - var firstMock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); - var secondMock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); - ComponentFactories.Add(firstMock); - ComponentFactories.Add(secondMock); - - RenderComponent(); - - firstMock.DidNotReceive().CanCreate(Arg.Any()); - firstMock.DidNotReceive().Create(Arg.Any()); - secondMock.Received(1).CanCreate(typeof(Simple1)); - secondMock.Received(1).Create(typeof(Simple1)); - } - - [Fact(DisplayName = "DisposeComponents captures exceptions from DisposeAsync in Renderer.UnhandledException")] - public async Task Test201() - { - var tcs = new TaskCompletionSource(); - var expected = new NotSupportedException(); - RenderComponent( - ps => ps.Add(p => p.DisposedTask, tcs.Task)); - - DisposeComponents(); - - tcs.SetException(expected); - var actual = await Renderer.UnhandledException; - actual.ShouldBeSameAs(expected); - } - - [Fact(DisplayName = "DisposeComponents calls DisposeAsync on rendered components")] - public async Task Test202() - { - var cut = RenderComponent(); - var wasDisposedTask = cut.Instance.DisposedTask; - - DisposeComponents(); - - await wasDisposedTask.ShouldCompleteWithin(TimeSpan.FromSeconds(1)); - } - - [Fact(DisplayName = "DisposeComponents should dispose components added via ComponentFactory")] - public void Test203() - { - ComponentFactories.Add(); - var cut = RenderComponent(ps => ps.Add(p => p.CallStack, new List())); - var instance = cut.FindComponent().Instance; - - DisposeComponents(); - - instance.WasDisposed.ShouldBeTrue(); - } - - [Fact(DisplayName = "Can correctly resolve and dispose of scoped disposable service")] - public void Net5Test001() - { - AsyncDisposableService asyncDisposable; - using (var sut = new TestContext()) - { - sut.Services.AddScoped(); - asyncDisposable = sut.Services.GetService(); - } - asyncDisposable.IsDisposed.ShouldBeTrue(); - } - - [Fact(DisplayName = "Can correctly resolve and dispose of transient disposable service")] - public void Net5Test002() - { - AsyncDisposableService asyncDisposable; - using (var sut = new TestContext()) - { - sut.Services.AddTransient(); - asyncDisposable = sut.Services.GetService(); - } - asyncDisposable.IsDisposed.ShouldBeTrue(); - } - - [Fact(DisplayName = "Can correctly resolve and dispose of singleton disposable service")] - public void Net5Test003() - { - AsyncDisposableService asyncDisposable; - using (var sut = new TestContext()) - { - sut.Services.AddSingleton(); - asyncDisposable = sut.Services.GetService(); - } - asyncDisposable.IsDisposed.ShouldBeTrue(); - } - - private sealed class AsyncDisposableService : IAsyncDisposable - { - public bool IsDisposed { get; private set; } - - public ValueTask DisposeAsync() - { - IsDisposed = true; - return ValueTask.CompletedTask; - } - } - - private sealed class MyChildDisposeStub : ComponentBase, IDisposable - { - public bool WasDisposed { get; private set; } - - public void Dispose() - { - WasDisposed = true; - } - } - - private sealed class AsyncThrowExceptionComponent : ComponentBase, IAsyncDisposable - { - [Parameter] - public Task DisposedTask { get; set; } - - public async ValueTask DisposeAsync() - { - await DisposedTask; - } - } - - private sealed class AsyncDisposableComponent : ComponentBase, IAsyncDisposable - { - private readonly TaskCompletionSource tsc = new(); - - public Task DisposedTask => tsc.Task; - - public async ValueTask DisposeAsync() - { - await Task.Delay(10); - tsc.SetResult(); - } - } - - private static IComponentFactory CreateMockComponentFactory(Func canCreate, Func create) - { - var result = Substitute.For(); - result.CanCreate(Arg.Any()).Returns(call => canCreate((Type)call[0])); - result.Create(Arg.Any()).Returns(call => create((Type)call[0])); - return result; - } -} diff --git a/tests/bunit.tests/TestContextTest.cs b/tests/bunit.tests/TestContextTest.cs index faa2fefa3..86049d7b9 100644 --- a/tests/bunit.tests/TestContextTest.cs +++ b/tests/bunit.tests/TestContextTest.cs @@ -1,9 +1,55 @@ +using Bunit.TestAssets.SampleComponents.DisposeComponents; using Bunit.TestDoubles; namespace Bunit; public partial class TestContextTest : TestContext { + [Fact(DisplayName = "DisposeComponents disposes rendered components in parent to child order")] + public void Test101() + { + var callStack = new List(); + RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); + + DisposeComponents(); + + callStack.Count.ShouldBe(2); + callStack[0].ShouldBe("ParentDispose"); + callStack[1].ShouldBe("ChildDispose"); + } + + [Fact(DisplayName = "DisposeComponents disposes multiple rendered components")] + public void Test102() + { + var callStack = new List(); + RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); + RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); + + DisposeComponents(); + + callStack.Count.ShouldBe(2); + } + + [Fact(DisplayName = "DisposeComponents rethrows exceptions from Dispose methods in components")] + public void Test103() + { + RenderComponent(); + var action = () => DisposeComponents(); + + action.ShouldThrow(); + } + + [Fact(DisplayName = "DisposeComponents disposes components nested in render fragments")] + public void Test104() + { + var callStack = new List(); + Render(DisposeFragments.ChildDisposeAsFragment(callStack)); + + DisposeComponents(); + + callStack.Count.ShouldBe(1); + } + [Fact(DisplayName = "The test service provider should register a placeholder HttpClient which throws exceptions")] public void Test024() { @@ -74,6 +120,127 @@ public void Test040() { Should.NotThrow(() => RenderComponent().Find("button").Click()); } + + [Fact(DisplayName = "TestContext should provide a default IErrorBoundaryLogger")] + public void Test001() + { + IErrorBoundaryLogger logger = Services.GetService(); + logger.ShouldNotBe(null); + } + + [Fact(DisplayName = "ComponentFactories CanCreate() method are checked during component instantiation")] + public void Test0001() + { + var mock = CreateMockComponentFactory(canCreate: _ => false, create: _ => null); + ComponentFactories.Add(mock); + + RenderComponent(); + + mock.Received(1).CanCreate(typeof(Simple1)); + mock.DidNotReceive().Create(Arg.Any()); + } + + [Fact(DisplayName = "ComponentFactories Create() method is called when their CanCreate() method returns true")] + public void Test0002() + { + var mock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); + ComponentFactories.Add(mock); + + RenderComponent(); + + mock.Received(1).CanCreate(typeof(Simple1)); + mock.Received(1).Create(typeof(Simple1)); + } + + [Fact(DisplayName = "ComponentFactories is used in last added order")] + public void Test0003() + { + var firstMock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); + var secondMock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); + ComponentFactories.Add(firstMock); + ComponentFactories.Add(secondMock); + + RenderComponent(); + + firstMock.DidNotReceive().CanCreate(Arg.Any()); + firstMock.DidNotReceive().Create(Arg.Any()); + secondMock.Received(1).CanCreate(typeof(Simple1)); + secondMock.Received(1).Create(typeof(Simple1)); + } + + [Fact(DisplayName = "DisposeComponents captures exceptions from DisposeAsync in Renderer.UnhandledException")] + public async Task Test201() + { + var tcs = new TaskCompletionSource(); + var expected = new NotSupportedException(); + RenderComponent( + ps => ps.Add(p => p.DisposedTask, tcs.Task)); + + DisposeComponents(); + + tcs.SetException(expected); + var actual = await Renderer.UnhandledException; + actual.ShouldBeSameAs(expected); + } + + [Fact(DisplayName = "DisposeComponents calls DisposeAsync on rendered components")] + public async Task Test202() + { + var cut = RenderComponent(); + var wasDisposedTask = cut.Instance.DisposedTask; + + DisposeComponents(); + + await wasDisposedTask.ShouldCompleteWithin(TimeSpan.FromSeconds(1)); + } + + [Fact(DisplayName = "DisposeComponents should dispose components added via ComponentFactory")] + public void Test203() + { + ComponentFactories.Add(); + var cut = RenderComponent(ps => ps.Add(p => p.CallStack, new List())); + var instance = cut.FindComponent().Instance; + + DisposeComponents(); + + instance.WasDisposed.ShouldBeTrue(); + } + + [Fact(DisplayName = "Can correctly resolve and dispose of scoped disposable service")] + public void Net5Test001() + { + AsyncDisposableService asyncDisposable; + using (var sut = new TestContext()) + { + sut.Services.AddScoped(); + asyncDisposable = sut.Services.GetService(); + } + asyncDisposable.IsDisposed.ShouldBeTrue(); + } + + [Fact(DisplayName = "Can correctly resolve and dispose of transient disposable service")] + public void Net5Test002() + { + AsyncDisposableService asyncDisposable; + using (var sut = new TestContext()) + { + sut.Services.AddTransient(); + asyncDisposable = sut.Services.GetService(); + } + asyncDisposable.IsDisposed.ShouldBeTrue(); + } + + [Fact(DisplayName = "Can correctly resolve and dispose of singleton disposable service")] + public void Net5Test003() + { + AsyncDisposableService asyncDisposable; + using (var sut = new TestContext()) + { + sut.Services.AddSingleton(); + asyncDisposable = sut.Services.GetService(); + } + asyncDisposable.IsDisposed.ShouldBeTrue(); + } private sealed class ReceivesCascadingValue : ComponentBase { @@ -81,4 +248,67 @@ private sealed class ReceivesCascadingValue : ComponentBase [Parameter] public object? Dummy { get; set; } } + + private sealed class ThrowExceptionComponent : ComponentBase, IDisposable + { + public void Dispose() + { +#pragma warning disable S3877 + throw new NotSupportedException(); +#pragma warning restore S3877 + } + } + + private sealed class AsyncDisposableService : IAsyncDisposable + { + public bool IsDisposed { get; private set; } + + public ValueTask DisposeAsync() + { + IsDisposed = true; + return ValueTask.CompletedTask; + } + } + + private sealed class MyChildDisposeStub : ComponentBase, IDisposable + { + public bool WasDisposed { get; private set; } + + public void Dispose() + { + WasDisposed = true; + } + } + + private sealed class AsyncThrowExceptionComponent : ComponentBase, IAsyncDisposable + { + [Parameter] + public Task DisposedTask { get; set; } + + public async ValueTask DisposeAsync() + { + await DisposedTask; + } + } + + private sealed class AsyncDisposableComponent : ComponentBase, IAsyncDisposable + { + private readonly TaskCompletionSource tsc = new(); + + public Task DisposedTask => tsc.Task; + + public async ValueTask DisposeAsync() + { + await Task.Delay(10); + tsc.SetResult(); + } + } + + private static IComponentFactory CreateMockComponentFactory(Func canCreate, Func create) + { + var result = Substitute.For(); + result.CanCreate(Arg.Any()).Returns(call => canCreate((Type)call[0])); + result.Create(Arg.Any()).Returns(call => create((Type)call[0])); + return result; + } } diff --git a/tests/bunit.tests/TestContextTest.net6.cs b/tests/bunit.tests/TestContextTest.net6.cs deleted file mode 100644 index 9ba770e7c..000000000 --- a/tests/bunit.tests/TestContextTest.net6.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Bunit; - -public partial class TestContextTest : TestContext -{ - [Fact(DisplayName = "TestContext should provide a default IErrorBoundaryLogger")] - public void Test001() - { - IErrorBoundaryLogger logger = Services.GetService(); - logger.ShouldNotBe(null); - } -} From d6478b985a36bc48a52d99798ada61bedf7033cc Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 11:18:19 +0100 Subject: [PATCH 010/100] refactor: Remove ITestRenderer interface --- src/bunit/Diffing/HtmlComparer.cs | 2 +- .../TriggerEventDispatchExtensions.cs | 10 +-- .../RenderedComponentRenderExtensions.cs | 2 +- .../RenderedFragmentInvokeAsyncExtensions.cs | 8 +- .../Extensions/TestRendererExtensions.cs | 6 +- .../WaitForHelpers/WaitForHelper.cs | 2 +- src/bunit/IRenderedFragment.cs | 6 +- src/bunit/Rendering/ITestRenderer.cs | 81 ------------------- src/bunit/Rendering/RenderEvent.cs | 2 +- src/bunit/Rendering/TestRenderer.cs | 4 +- src/bunit/TestContext.cs | 4 +- src/bunit/TestContextWrapper.cs | 2 +- .../BunitPersistentComponentState.cs | 4 +- 13 files changed, 26 insertions(+), 107 deletions(-) delete mode 100644 src/bunit/Rendering/ITestRenderer.cs diff --git a/src/bunit/Diffing/HtmlComparer.cs b/src/bunit/Diffing/HtmlComparer.cs index b88027e23..2dd73d112 100644 --- a/src/bunit/Diffing/HtmlComparer.cs +++ b/src/bunit/Diffing/HtmlComparer.cs @@ -8,7 +8,7 @@ namespace Bunit.Diffing; /// -/// Represents a test HTML comparer, that is configured to work with markup generated by the and classes. +/// Represents a test HTML comparer, that is configured to work with markup generated by the and classes. /// public sealed class HtmlComparer { diff --git a/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs index 2a243b8b1..62e44e9a1 100644 --- a/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs +++ b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs @@ -63,7 +63,7 @@ public static Task TriggerEventAsync(this IElement element, string eventName, Ev ArgumentNullException.ThrowIfNull(eventName); var renderer = element.GetTestContext()?.Renderer - ?? throw new InvalidOperationException($"Blazor events can only be raised on elements rendered with the Blazor test renderer '{nameof(ITestRenderer)}'."); + ?? throw new InvalidOperationException($"Blazor events can only be raised on elements rendered with the Blazor test renderer '{nameof(TestRenderer)}'."); // TriggerEventsAsync will traverse the DOM tree to find // all event handlers that needs to be triggered. This is done @@ -78,7 +78,7 @@ public static Task TriggerEventAsync(this IElement element, string eventName, Ev } [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "HTML events are standardize to lower case and safe in this context.")] - private static Task TriggerEventsAsync(ITestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) + private static Task TriggerEventsAsync(TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) { var isNonBubblingEvent = NonBubblingEvents.Contains(eventName.ToLowerInvariant()); var unwrappedElement = element.Unwrap(); @@ -88,7 +88,7 @@ private static Task TriggerEventsAsync(ITestRenderer renderer, IElement element, : TriggerBubblingEventAsync(renderer, unwrappedElement, eventName, eventArgs); } - private static Task TriggerNonBubblingEventAsync(ITestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) + private static Task TriggerNonBubblingEventAsync(TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) { var eventAttrName = Htmlizer.ToBlazorAttribute(eventName); @@ -105,7 +105,7 @@ private static Task TriggerNonBubblingEventAsync(ITestRenderer renderer, IElemen throw new MissingEventHandlerException(element, eventName); } - private static Task TriggerBubblingEventAsync(ITestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) + private static Task TriggerBubblingEventAsync(TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) { var eventTasks = GetDispatchEventTasks(renderer, element, eventName, eventArgs); @@ -118,7 +118,7 @@ private static Task TriggerBubblingEventAsync(ITestRenderer renderer, IElement e } private static List GetDispatchEventTasks( - ITestRenderer renderer, + TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) diff --git a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs index a25be08e3..8efe2f5d2 100644 --- a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs @@ -28,7 +28,7 @@ public static void SetParametersAndRender(this IRenderedComponent().Renderer; + var renderer = renderedComponent.Services.GetRequiredService().Renderer; try { diff --git a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index 974a99dd4..88abb6cf2 100644 --- a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -8,7 +8,7 @@ namespace Bunit; public static class RenderedFragmentInvokeAsyncExtensions { /// - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered fragment whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. @@ -26,7 +26,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Action w } /// - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. @@ -44,7 +44,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. @@ -62,7 +62,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Fu } /// - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. diff --git a/src/bunit/Extensions/TestRendererExtensions.cs b/src/bunit/Extensions/TestRendererExtensions.cs index d1b6243a5..074028a38 100644 --- a/src/bunit/Extensions/TestRendererExtensions.cs +++ b/src/bunit/Extensions/TestRendererExtensions.cs @@ -3,7 +3,7 @@ namespace Bunit.Extensions; /// -/// Helper methods that make it easier to work directly with a +/// Helper methods that make it easier to work directly with a /// in bUnit web. /// public static class TestRendererExtensions @@ -15,7 +15,7 @@ public static class TestRendererExtensions /// The renderer to use. /// The parameters to pass to the component. /// A that provides access to the rendered component. - public static IRenderedComponent RenderComponent(this ITestRenderer renderer, params ComponentParameter[] parameters) + public static IRenderedComponent RenderComponent(this TestRenderer renderer, params ComponentParameter[] parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); @@ -34,7 +34,7 @@ public static IRenderedComponent RenderComponent(this IT /// The renderer to use. /// The a builder to create parameters to pass to the component. /// A that provides access to the rendered component. - public static IRenderedComponent RenderComponent(this ITestRenderer renderer, Action> parameterBuilder) + public static IRenderedComponent RenderComponent(this TestRenderer renderer, Action> parameterBuilder) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index 6408dcf5b..650ccccea 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -54,7 +54,7 @@ protected WaitForHelper( this.completeChecker = completeChecker ?? throw new ArgumentNullException(nameof(completeChecker)); logger = renderedFragment.Services.CreateLogger>(); - renderer = (TestRenderer)renderedFragment + renderer = renderedFragment .Services .GetRequiredService() .Renderer; diff --git a/src/bunit/IRenderedFragment.cs b/src/bunit/IRenderedFragment.cs index 61a1a0192..ebf887a3d 100644 --- a/src/bunit/IRenderedFragment.cs +++ b/src/bunit/IRenderedFragment.cs @@ -14,7 +14,7 @@ public interface IRenderedFragment : IDisposable int RenderCount { get; } /// - /// Gets a value indicating whether the rendered component or fragment has been disposed by the . + /// Gets a value indicating whether the rendered component or fragment has been disposed by the . /// bool IsDisposed { get; } @@ -24,7 +24,7 @@ public interface IRenderedFragment : IDisposable int ComponentId { get; } /// - /// Called by the owning when it finishes a render. + /// Called by the owning when it finishes a render. /// /// A that represents a render. void OnRender(RenderEvent renderEvent); @@ -51,6 +51,6 @@ public interface IRenderedFragment : IDisposable /// /// Gets the AngleSharp based /// on the HTML markup from the rendered fragment/component. - /// + /// INodeList Nodes { get; } } diff --git a/src/bunit/Rendering/ITestRenderer.cs b/src/bunit/Rendering/ITestRenderer.cs deleted file mode 100644 index 5e445dec0..000000000 --- a/src/bunit/Rendering/ITestRenderer.cs +++ /dev/null @@ -1,81 +0,0 @@ -namespace Bunit.Rendering; - -/// -/// Represents a generalized Blazor renderer for testing purposes. -/// -public interface ITestRenderer -{ - /// - /// Gets a , which completes when an unhandled exception - /// is thrown during the rendering of a component, that is caught by the renderer. - /// - Task UnhandledException { get; } - - /// - /// Gets the associated with this . - /// - Dispatcher Dispatcher { get; } - - /// - /// Notifies the renderer that an event has occurred. - /// - /// The value from the original event attribute. - /// Information that the renderer can use to update the state of the existing render tree to match the UI. - /// Arguments to be passed to the event handler. - /// A which will complete once all asynchronous processing related to the event has completed. - Task DispatchEventAsync( - ulong eventHandlerId, - EventFieldInfo fieldInfo, - EventArgs eventArgs); - - /// - /// Notifies the renderer that an event has occurred. - /// - /// The value from the original event attribute. - /// Information that the renderer can use to update the state of the existing render tree to match the UI. - /// Arguments to be passed to the event handler. - /// Set to true to ignore the . - /// A which will complete once all asynchronous processing related to the event has completed. - Task DispatchEventAsync( - ulong eventHandlerId, - EventFieldInfo fieldInfo, - EventArgs eventArgs, - bool ignoreUnknownEventHandlers); - - /// - /// Renders the . - /// - /// The to render. - /// A that provides access to the rendered . - IRenderedFragment RenderFragment(RenderFragment renderFragment); - - /// - /// Renders a with the passed to it. - /// - /// The type of component to render. - /// The parameters to pass to the component. - /// A that provides access to the rendered component. - IRenderedComponent RenderComponent(ComponentParameterCollection parameters) - where TComponent : IComponent; - - /// - /// Performs a depth-first search for the first child component of the . - /// - /// Type of component to find. - /// Parent component to search. - IRenderedComponent FindComponent(IRenderedFragment parentComponent) - where TComponent : IComponent; - - /// - /// Performs a depth-first search for all child components of the . - /// - /// Type of components to find. - /// Parent component to search. - IReadOnlyList> FindComponents(IRenderedFragment parentComponent) - where TComponent : IComponent; - - /// - /// Disposes all components rendered by the . - /// - void DisposeComponents(); -} diff --git a/src/bunit/Rendering/RenderEvent.cs b/src/bunit/Rendering/RenderEvent.cs index cd8561e16..9069cb786 100644 --- a/src/bunit/Rendering/RenderEvent.cs +++ b/src/bunit/Rendering/RenderEvent.cs @@ -1,7 +1,7 @@ namespace Bunit.Rendering; /// -/// Represents an render event from a . +/// Represents an render event from a . /// public sealed class RenderEvent { diff --git a/src/bunit/Rendering/TestRenderer.cs b/src/bunit/Rendering/TestRenderer.cs index 06e787d62..984d7434e 100644 --- a/src/bunit/Rendering/TestRenderer.cs +++ b/src/bunit/Rendering/TestRenderer.cs @@ -6,9 +6,9 @@ namespace Bunit.Rendering; /// -/// Represents a bUnit used to render Blazor components and fragments during bUnit tests. +/// Represents a bUnit used to render Blazor components and fragments during bUnit tests. /// -public class TestRenderer : Renderer, ITestRenderer +public sealed class TestRenderer : Renderer { [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")] extern static ref bool GetIsBatchInProgressField(Renderer renderer); diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index de3286aa6..47d492202 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -10,7 +10,7 @@ namespace Bunit; public class TestContext : IDisposable { private bool disposed; - private ITestRenderer? testRenderer; + private TestRenderer? testRenderer; /// /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . @@ -21,7 +21,7 @@ public class TestContext : IDisposable /// /// Gets the renderer used by the test context. /// - public ITestRenderer Renderer => testRenderer ??= CreateTestRenderer(); + public TestRenderer Renderer => testRenderer ??= CreateTestRenderer(); /// /// Gets bUnits JSInterop, that allows setting up handlers for invocations diff --git a/src/bunit/TestContextWrapper.cs b/src/bunit/TestContextWrapper.cs index a6a9c57c0..8afa6b4f8 100644 --- a/src/bunit/TestContextWrapper.cs +++ b/src/bunit/TestContextWrapper.cs @@ -17,7 +17,7 @@ public abstract class TestContextWrapper /// /// Gets the renderer used by the test context. /// - public ITestRenderer Renderer => TestContext?.Renderer ?? throw new InvalidOperationException("The TestContext has not been initialized."); + public TestRenderer Renderer => TestContext?.Renderer ?? throw new InvalidOperationException("The TestContext has not been initialized."); /// /// Gets the service collection and service provider that is used when a diff --git a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs index d6ae10f98..ae8b12f58 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs @@ -17,7 +17,7 @@ public sealed class BunitPersistentComponentState }; private readonly BunitPersistentComponentStateStore store; private readonly Lazy manager; - private readonly Lazy renderer; + private readonly Lazy renderer; /// /// Initializes a new instance of the class. @@ -27,7 +27,7 @@ internal BunitPersistentComponentState(IServiceProvider services) { store = new BunitPersistentComponentStateStore(); manager = new Lazy(() => services.GetRequiredService()); - renderer = new Lazy(() => services.GetRequiredService().Renderer); + renderer = new Lazy(() => services.GetRequiredService().Renderer); } /// From e02f42a2fa80ad4f4167f13debe33ea63769ee7a Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 11:29:25 +0100 Subject: [PATCH 011/100] refactor: Remove abstraction around RenderedFragment/RenderedComponent --- MIGRATION.md | 6 +- .../docs/getting-started/writing-tests.md | 2 +- .../docs/interaction/awaiting-async-state.md | 4 +- .../docs/interaction/dispose-components.md | 2 +- .../interaction/trigger-event-handlers.md | 4 +- docs/site/docs/interaction/trigger-renders.md | 20 +-- .../passing-parameters-to-components.md | 4 +- .../substituting-components.md | 14 +- docs/site/docs/test-doubles/input-file.md | 4 +- .../site/docs/verification/async-assertion.md | 4 +- .../verification/verify-component-state.md | 18 +-- docs/site/docs/verification/verify-markup.md | 6 +- src/bunit/Asserting/CompareToExtensions.cs | 10 +- .../MarkupMatchesAssertExtensions.cs | 40 +++--- .../IRefreshableElementCollection.cs | 4 +- .../InputFile/InputFileExtensions.cs | 2 +- .../Internal/CssSelectorElementFactory.cs | 4 +- .../Internal/RefreshableElementCollection.cs | 4 +- .../RenderedComponentRenderExtensions.cs | 10 +- .../Extensions/RenderedFragmentExtensions.cs | 22 +-- .../RenderedFragmentInvokeAsyncExtensions.cs | 10 +- .../Extensions/TestContextRenderExtensions.cs | 8 +- .../Extensions/TestRendererExtensions.cs | 12 +- ...tWaitForHelperExtensions.WaitForElement.cs | 32 ++--- ...entWaitForHelperExtensions.WaitForState.cs | 8 +- .../WaitForHelpers/WaitForAssertionHelper.cs | 2 +- .../WaitForHelpers/WaitForElementHelper.cs | 2 +- .../WaitForHelpers/WaitForElementsHelper.cs | 2 +- .../WaitForHelpers/WaitForHelper.cs | 6 +- .../WaitForHelpers/WaitForStateHelper.cs | 2 +- src/bunit/IRenderedComponent.cs | 11 -- src/bunit/IRenderedFragment.cs | 56 -------- .../Rendering/ComponentDisposedException.cs | 2 +- .../Rendering/IRenderedComponentActivator.cs | 14 +- src/bunit/Rendering/RenderEvent.cs | 2 +- src/bunit/Rendering/RenderedComponent.cs | 16 ++- .../Rendering/RenderedComponentActivator.cs | 6 +- src/bunit/Rendering/RenderedFragment.cs | 133 +++++++++--------- src/bunit/Rendering/TestRenderer.cs | 22 +-- src/bunit/TestContext.cs | 16 +-- src/bunit/TestContextWrapper.cs | 14 +- .../CompareToDiffingExtensionsTest.cs | 4 +- .../MarkupMatchesAssertExtensionsTest.cs | 22 +-- ...omponentParameterCollectionBuilderTests.cs | 14 +- .../ComponentParameterCollectionTest.cs | 2 +- .../ComponentParameterFactoryTest.cs | 2 +- .../TriggerEventSpy.cs | 4 +- .../Extensions/InputFile/InputFileTests.cs | 2 +- .../bunit.tests/Rendering/TestRendererTest.cs | 2 +- .../TestUtilities/MockingHelpers.cs | 22 +++ 50 files changed, 300 insertions(+), 334 deletions(-) delete mode 100644 src/bunit/IRenderedComponent.cs delete mode 100644 src/bunit/IRenderedFragment.cs diff --git a/MIGRATION.md b/MIGRATION.md index 675181a74..29339e908 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -2,7 +2,7 @@ This document describes the changes that need to be made to migrate from bUnit 1.x to 2.x. ## Removal of `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods -The `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods have been removed from `IRenderedComponent`. There is no one-to-one replacement for these methods, but the general idea is to select the HTML in question via `Find` and assert against that. +The `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods have been removed from `RenderedComponent`. There is no one-to-one replacement for these methods, but the general idea is to select the HTML in question via `Find` and assert against that. Alternatively, the `IRenderFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. @@ -28,8 +28,8 @@ The `bunit.core` and `bunit.web` packages have been merged into a single `bunit` ## Removal of unneeded abstraction -### `IRenderedComponentBase` and `IRenderedFragmentBase` -`IRenderedComponentBase` and `IRenderedFragmentBase` have been removed. They were used to provide a common base class for `IRenderedComponent` and `IRenderedFragment`, but this is no longer needed (due to the merge of the project). If you used either of these interfaces, you should replace them with `IRenderedComponent` and `IRenderedFragment` respectively. +### `IRenderedComponentBase` and `RenderedFragmentBase` +`IRenderedComponentBase` and `RenderedFragmentBase` have been removed. They were used to provide a common base class for `RenderedComponent` and `RenderedFragment`, but this is no longer needed (due to the merge of the project). If you used either of these interfaces, you should replace them with `RenderedComponent` and `RenderedFragment` respectively. ### `WebTestRender` merged into `TestRender` The `WebTestRender` class has been merged into the `TestRender` class. If you used `WebTestRender`, you should replace it with `TestRender`. diff --git a/docs/site/docs/getting-started/writing-tests.md b/docs/site/docs/getting-started/writing-tests.md index 1c9663b4e..3b89e9a9e 100644 --- a/docs/site/docs/getting-started/writing-tests.md +++ b/docs/site/docs/getting-started/writing-tests.md @@ -9,7 +9,7 @@ Testing Blazor components is a little different from testing regular C# classes: Use **bUnit** to render the component under test, pass in its parameters, inject required services, and access the rendered component instance and the markup it has produced. -Rendering a component happens through bUnit's . The result of the rendering is an `IRenderedComponent`, referred to as a "rendered component", that provides access to the component instance and the markup produced by the component. +Rendering a component happens through bUnit's . The result of the rendering is an `RenderedComponent`, referred to as a "rendered component", that provides access to the component instance and the markup produced by the component. ## Write tests in `.cs` or `.razor` files diff --git a/docs/site/docs/interaction/awaiting-async-state.md b/docs/site/docs/interaction/awaiting-async-state.md index 2d7c668af..165a59e16 100644 --- a/docs/site/docs/interaction/awaiting-async-state.md +++ b/docs/site/docs/interaction/awaiting-async-state.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) method covered on the page. Let's start by taking a look at the `WaitForState` method in more detail. ## Waiting for state using `WaitForState` -The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) +The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) > [!NOTE] > The `WaitForState()` method will try the predicate passed to it when the `WaitForState()` method is called, and every time the component under test renders. diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index b996b67a7..984e5389c 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -13,7 +13,7 @@ The following example of this: [!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] > [!WARNING] -> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.IRenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.IRenderedFragment,Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. +> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Checking for exceptions `Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.TestContext.DisposeComponents) will throw the exception to the user code: diff --git a/docs/site/docs/interaction/trigger-event-handlers.md b/docs/site/docs/interaction/trigger-event-handlers.md index 8b1245ccd..89e148f48 100644 --- a/docs/site/docs/interaction/trigger-event-handlers.md +++ b/docs/site/docs/interaction/trigger-event-handlers.md @@ -23,7 +23,7 @@ bUnit comes with event dispatch helper methods that makes it possible to invoke - [Progress events](xref:Bunit.ProgressEventDispatchExtensions) - [Touch event](xref:Bunit.TouchEventDispatchExtensions) -To use these, first find the element in the component under test where the event handler is bound. This is usually done with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method. Next, invoke the event dispatch helper method of choice. +To use these, first find the element in the component under test where the event handler is bound. This is usually done with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.RenderedFragment,System.String)) method. Next, invoke the event dispatch helper method of choice. The following section demonstrates how to do this... @@ -49,7 +49,7 @@ To trigger the `@onclick` `ClickHandler` event handler method in the `` This is what happens in the test: -1. In the arrange step of the test, the `` component is rendered and the ` /// The rendered component to re-render. /// The type of the component. - public static void Render(this IRenderedComponent renderedComponent) + public static void Render(this RenderedComponent renderedComponent) where TComponent : IComponent => SetParametersAndRender(renderedComponent, ParameterView.Empty); @@ -23,7 +23,7 @@ public static void Render(this IRenderedComponent render /// The rendered component to re-render with new parameters. /// Parameters to pass to the component upon rendered. /// The type of the component. - public static void SetParametersAndRender(this IRenderedComponent renderedComponent, ParameterView parameters) + public static void SetParametersAndRender(this RenderedComponent renderedComponent, ParameterView parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); @@ -46,7 +46,7 @@ public static void SetParametersAndRender(this IRenderedComponentThe rendered component to re-render with new parameters. /// Parameters to pass to the component upon rendered. /// The type of the component. - public static void SetParametersAndRender(this IRenderedComponent renderedComponent, params ComponentParameter[] parameters) + public static void SetParametersAndRender(this RenderedComponent renderedComponent, params ComponentParameter[] parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); @@ -61,7 +61,7 @@ public static void SetParametersAndRender(this IRenderedComponentThe rendered component to re-render with new parameters. /// An action that receives a . /// The type of the component. - public static void SetParametersAndRender(this IRenderedComponent renderedComponent, Action> parameterBuilder) + public static void SetParametersAndRender(this RenderedComponent renderedComponent, Action> parameterBuilder) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); diff --git a/src/bunit/Extensions/RenderedFragmentExtensions.cs b/src/bunit/Extensions/RenderedFragmentExtensions.cs index 83732d052..e2f6d0070 100644 --- a/src/bunit/Extensions/RenderedFragmentExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentExtensions.cs @@ -5,7 +5,7 @@ namespace Bunit; /// -/// Helper methods for querying . +/// Helper methods for querying . /// public static class RenderedFragmentExtensions { @@ -16,7 +16,7 @@ public static class RenderedFragmentExtensions /// /// The rendered fragment to search. /// The group of selectors to use. - public static IElement Find(this IRenderedFragment renderedFragment, string cssSelector) + public static IElement Find(this RenderedFragment renderedFragment, string cssSelector) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -37,7 +37,7 @@ public static IElement Find(this IRenderedFragment renderedFragment, string cssS /// The group of selectors to use. /// If true, the returned will automatically refresh its s whenever the changes. /// An , that can be refreshed to execute the search again. - public static IRefreshableElementCollection FindAll(this IRenderedFragment renderedFragment, string cssSelector, bool enableAutoRefresh = false) + public static IRefreshableElementCollection FindAll(this RenderedFragment renderedFragment, string cssSelector, bool enableAutoRefresh = false) { ArgumentNullException.ThrowIfNull(renderedFragment); return new RefreshableElementCollection(renderedFragment, cssSelector) { EnableAutoRefresh = enableAutoRefresh }; @@ -45,12 +45,12 @@ public static IRefreshableElementCollection FindAll(this IRenderedFrag /// /// Finds the first component of type in the render tree of - /// this . + /// this . /// /// Type of component to find. /// Thrown if a component of type was not found in the render tree. - /// The . - public static IRenderedComponent FindComponent(this IRenderedFragment renderedFragment) + /// The . + public static RenderedComponent FindComponent(this RenderedFragment renderedFragment) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -61,11 +61,11 @@ public static IRenderedComponent FindComponent(this IRen /// /// Finds all components of type in the render tree of - /// this , in depth-first order. + /// this , in depth-first order. /// /// Type of components to find. - /// The s. - public static IReadOnlyList> FindComponents(this IRenderedFragment renderedFragment) + /// The s. + public static IReadOnlyList> FindComponents(this RenderedFragment renderedFragment) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -73,7 +73,7 @@ public static IReadOnlyList> FindComponents().Renderer; var components = renderer.FindComponents(renderedFragment); - return components.OfType>().ToArray(); + return components.OfType>().ToArray(); } /// @@ -83,6 +83,6 @@ public static IReadOnlyList> FindComponentsThe type of component to look for in the render tree. /// The render tree to search. /// True if the contains the ; otherwise false. - public static bool HasComponent(this IRenderedFragment renderedFragment) + public static bool HasComponent(this RenderedFragment renderedFragment) where TComponent : IComponent => FindComponents(renderedFragment).Count > 0; } diff --git a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index 88abb6cf2..232eaa875 100644 --- a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -3,7 +3,7 @@ namespace Bunit; /// -/// InvokeAsync extensions methods on . +/// InvokeAsync extensions methods on . /// public static class RenderedFragmentInvokeAsyncExtensions { @@ -13,7 +13,7 @@ public static class RenderedFragmentInvokeAsyncExtensions /// The rendered fragment whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing or is suspended by an asynchronous operation. - public static Task InvokeAsync(this IRenderedFragment renderedFragment, Action workItem) + public static Task InvokeAsync(this RenderedFragment renderedFragment, Action workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -31,7 +31,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Action w /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing. - public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func workItem) + public static Task InvokeAsync(this RenderedFragment renderedFragment, Func workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -49,7 +49,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, FuncThe rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing, with the return value from . - public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func workItem) + public static Task InvokeAsync(this RenderedFragment renderedFragment, Func workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); @@ -67,7 +67,7 @@ public static Task InvokeAsync(this IRenderedFragment renderedFragment, Fu /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. /// A that will be completed when the action has finished executing, with the return value from . - public static Task InvokeAsync(this IRenderedFragment renderedFragment, Func> workItem) + public static Task InvokeAsync(this RenderedFragment renderedFragment, Func> workItem) { ArgumentNullException.ThrowIfNull(renderedFragment); diff --git a/src/bunit/Extensions/TestContextRenderExtensions.cs b/src/bunit/Extensions/TestContextRenderExtensions.cs index cd11843fa..d2d369970 100644 --- a/src/bunit/Extensions/TestContextRenderExtensions.cs +++ b/src/bunit/Extensions/TestContextRenderExtensions.cs @@ -13,8 +13,8 @@ public static class TestContextRenderExtensions /// The type of component to render. /// Test context to use to render with. /// The that contains a declaration of the component. - /// A . - public static IRenderedComponent RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) + /// A . + public static RenderedComponent RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(testContext); @@ -28,8 +28,8 @@ public static IRenderedComponent RenderInsideRenderTree( /// /// Test context to use to render with. /// The to render. - /// A . - public static IRenderedFragment RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) + /// A . + public static RenderedFragment RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) { ArgumentNullException.ThrowIfNull(testContext); diff --git a/src/bunit/Extensions/TestRendererExtensions.cs b/src/bunit/Extensions/TestRendererExtensions.cs index 074028a38..31d9817f7 100644 --- a/src/bunit/Extensions/TestRendererExtensions.cs +++ b/src/bunit/Extensions/TestRendererExtensions.cs @@ -14,14 +14,14 @@ public static class TestRendererExtensions /// The type of component to render. /// The renderer to use. /// The parameters to pass to the component. - /// A that provides access to the rendered component. - public static IRenderedComponent RenderComponent(this TestRenderer renderer, params ComponentParameter[] parameters) + /// A that provides access to the rendered component. + public static RenderedComponent RenderComponent(this TestRenderer renderer, params ComponentParameter[] parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); var resultBase = renderer.RenderComponent(new ComponentParameterCollection { parameters }); - if (resultBase is IRenderedComponent result) + if (resultBase is RenderedComponent result) return result; throw new InvalidOperationException($"The renderer did not produce the expected type. Is the test renderer using the expected {nameof(IRenderedComponentActivator)}?"); @@ -33,8 +33,8 @@ public static IRenderedComponent RenderComponent(this Te /// The type of component to render. /// The renderer to use. /// The a builder to create parameters to pass to the component. - /// A that provides access to the rendered component. - public static IRenderedComponent RenderComponent(this TestRenderer renderer, Action> parameterBuilder) + /// A that provides access to the rendered component. + public static RenderedComponent RenderComponent(this TestRenderer renderer, Action> parameterBuilder) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); @@ -42,7 +42,7 @@ public static IRenderedComponent RenderComponent(this Te var builder = new ComponentParameterCollectionBuilder(parameterBuilder); var resultBase = renderer.RenderComponent(builder.Build()); - if (resultBase is IRenderedComponent result) + if (resultBase is RenderedComponent result) return result; throw new InvalidOperationException($"The renderer did not produce the expected type. Is the test renderer using the expected {nameof(IRenderedComponentActivator)}?"); diff --git a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs index f6fac5d47..910374624 100644 --- a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs +++ b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForElement.cs @@ -17,7 +17,7 @@ public static partial class RenderedFragmentWaitForHelperExtensions /// The CSS selector to use to search for the element. /// Thrown if no elements is found matching the within the default timeout. See the inner exception for details. /// The . - public static IElement WaitForElement(this IRenderedFragment renderedFragment, string cssSelector) + public static IElement WaitForElement(this RenderedFragment renderedFragment, string cssSelector) => WaitForElementCore(renderedFragment, cssSelector, timeout: null); /// @@ -29,7 +29,7 @@ public static IElement WaitForElement(this IRenderedFragment renderedFragment, s /// The maximum time to wait for the element to appear. /// Thrown if no elements is found matching the within the default timeout. See the inner exception for details. /// The . - public static IElement WaitForElement(this IRenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) + public static IElement WaitForElement(this RenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) => WaitForElementCore(renderedFragment, cssSelector, timeout: timeout); /// @@ -40,7 +40,7 @@ public static IElement WaitForElement(this IRenderedFragment renderedFragment, s /// The CSS selector to use to search for elements. /// Thrown if no elements is found matching the within the default timeout. /// The . - public static IRefreshableElementCollection WaitForElements(this IRenderedFragment renderedFragment, string cssSelector) + public static IRefreshableElementCollection WaitForElements(this RenderedFragment renderedFragment, string cssSelector) => WaitForElementsCore(renderedFragment, cssSelector, matchElementCount: null, timeout: null); /// @@ -52,7 +52,7 @@ public static IRefreshableElementCollection WaitForElements(this IRend /// The exact number of elements to that the should match. /// Thrown if no elements is found matching the within the default timeout. /// The . - public static IRefreshableElementCollection WaitForElements(this IRenderedFragment renderedFragment, string cssSelector, int matchElementCount) + public static IRefreshableElementCollection WaitForElements(this RenderedFragment renderedFragment, string cssSelector, int matchElementCount) => WaitForElementsCore(renderedFragment, cssSelector, matchElementCount: matchElementCount, timeout: null); /// @@ -64,7 +64,7 @@ public static IRefreshableElementCollection WaitForElements(this IRend /// The maximum time to wait for elements to appear. /// Thrown if no elements is found matching the within the default timeout. /// The . - public static IRefreshableElementCollection WaitForElements(this IRenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) + public static IRefreshableElementCollection WaitForElements(this RenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) => WaitForElementsCore(renderedFragment, cssSelector, matchElementCount: null, timeout: timeout); /// @@ -77,7 +77,7 @@ public static IRefreshableElementCollection WaitForElements(this IRend /// The maximum time to wait for elements to appear. /// Thrown if no elements is found matching the within the default timeout. /// The . - public static IRefreshableElementCollection WaitForElements(this IRenderedFragment renderedFragment, string cssSelector, int matchElementCount, TimeSpan timeout) + public static IRefreshableElementCollection WaitForElements(this RenderedFragment renderedFragment, string cssSelector, int matchElementCount, TimeSpan timeout) => WaitForElementsCore(renderedFragment, cssSelector, matchElementCount: matchElementCount, timeout: timeout); /// @@ -88,7 +88,7 @@ public static IRefreshableElementCollection WaitForElements(this IRend /// The CSS selector to use to search for the element. /// Thrown if no elements is found matching the within the default timeout. See the inner exception for details. /// The . - internal static Task WaitForElementAsync(this IRenderedFragment renderedFragment, string cssSelector) + internal static Task WaitForElementAsync(this RenderedFragment renderedFragment, string cssSelector) => WaitForElementCoreAsync(renderedFragment, cssSelector, timeout: null); /// @@ -100,7 +100,7 @@ internal static Task WaitForElementAsync(this IRenderedFragment render /// The maximum time to wait for the element to appear. /// Thrown if no elements is found matching the within the default timeout. See the inner exception for details. /// The . - internal static Task WaitForElementAsync(this IRenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) + internal static Task WaitForElementAsync(this RenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) => WaitForElementCoreAsync(renderedFragment, cssSelector, timeout: timeout); /// @@ -112,7 +112,7 @@ internal static Task WaitForElementAsync(this IRenderedFragment render /// The exact number of elements to that the should match. /// Thrown if no elements is found matching the within the default timeout. /// The . - internal static Task> WaitForElementsAsync(this IRenderedFragment renderedFragment, string cssSelector, int matchElementCount) + internal static Task> WaitForElementsAsync(this RenderedFragment renderedFragment, string cssSelector, int matchElementCount) => WaitForElementsCoreAsync(renderedFragment, cssSelector, matchElementCount: matchElementCount, timeout: null); /// @@ -124,7 +124,7 @@ internal static Task> WaitForElementsAsy /// The maximum time to wait for elements to appear. /// Thrown if no elements is found matching the within the default timeout. /// The . - internal static Task> WaitForElementsAsync(this IRenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) + internal static Task> WaitForElementsAsync(this RenderedFragment renderedFragment, string cssSelector, TimeSpan timeout) => WaitForElementsCoreAsync(renderedFragment, cssSelector, matchElementCount: null, timeout: timeout); /// @@ -137,7 +137,7 @@ internal static Task> WaitForElementsAsy /// The maximum time to wait for elements to appear. /// Thrown if no elements is found matching the within the default timeout. /// The . - internal static Task> WaitForElementsAsync(this IRenderedFragment renderedFragment, string cssSelector, int matchElementCount, TimeSpan timeout) + internal static Task> WaitForElementsAsync(this RenderedFragment renderedFragment, string cssSelector, int matchElementCount, TimeSpan timeout) => WaitForElementsCoreAsync(renderedFragment, cssSelector, matchElementCount: matchElementCount, timeout: timeout); /// @@ -148,10 +148,10 @@ internal static Task> WaitForElementsAsy /// The CSS selector to use to search for elements. /// Thrown if no elements is found matching the within the default timeout. /// The . - internal static Task> WaitForElementsAsync(this IRenderedFragment renderedFragment, string cssSelector) + internal static Task> WaitForElementsAsync(this RenderedFragment renderedFragment, string cssSelector) => WaitForElementsCoreAsync(renderedFragment, cssSelector, matchElementCount: null, timeout: null); - private static IElement WaitForElementCore(this IRenderedFragment renderedFragment, string cssSelector, TimeSpan? timeout) + private static IElement WaitForElementCore(this RenderedFragment renderedFragment, string cssSelector, TimeSpan? timeout) { using var waiter = new WaitForElementHelper(renderedFragment, cssSelector, timeout); @@ -168,7 +168,7 @@ private static IElement WaitForElementCore(this IRenderedFragment renderedFragme } } - private static async Task WaitForElementCoreAsync(this IRenderedFragment renderedFragment, string cssSelector, TimeSpan? timeout) + private static async Task WaitForElementCoreAsync(this RenderedFragment renderedFragment, string cssSelector, TimeSpan? timeout) { using var waiter = new WaitForElementHelper(renderedFragment, cssSelector, timeout); @@ -176,7 +176,7 @@ private static async Task WaitForElementCoreAsync(this IRenderedFragme } private static IRefreshableElementCollection WaitForElementsCore( - this IRenderedFragment renderedFragment, + this RenderedFragment renderedFragment, string cssSelector, int? matchElementCount, TimeSpan? timeout) @@ -197,7 +197,7 @@ private static IRefreshableElementCollection WaitForElementsCore( } private static async Task> WaitForElementsCoreAsync( - this IRenderedFragment renderedFragment, + this RenderedFragment renderedFragment, string cssSelector, int? matchElementCount, TimeSpan? timeout) diff --git a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs index f2eb51d49..4cdfdfecc 100644 --- a/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs +++ b/src/bunit/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensions.WaitForState.cs @@ -23,7 +23,7 @@ public static partial class RenderedFragmentWaitForHelperExtensions /// /// If a debugger is attached the timeout is set to , giving the possibility to debug without the timeout triggering. /// - public static void WaitForState(this IRenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) + public static void WaitForState(this RenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) { using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); @@ -48,7 +48,7 @@ public static void WaitForState(this IRenderedFragment renderedFragment, FuncThe predicate to invoke after each render, which must returns true when the desired state has been reached. /// The maximum time to wait for the desired state. /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. - internal static async Task WaitForStateAsync(this IRenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) + internal static async Task WaitForStateAsync(this RenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) { using var waiter = new WaitForStateHelper(renderedFragment, statePredicate, timeout); @@ -66,7 +66,7 @@ internal static async Task WaitForStateAsync(this IRenderedFragment renderedFrag /// The maximum time to attempt the verification. /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. [AssertionMethod] - public static void WaitForAssertion(this IRenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) + public static void WaitForAssertion(this RenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) { using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); @@ -91,7 +91,7 @@ public static void WaitForAssertion(this IRenderedFragment renderedFragment, Act /// The maximum time to attempt the verification. /// Thrown if the timeout has been reached. See the inner exception to see the captured assertion exception. [AssertionMethod] - internal static async Task WaitForAssertionAsync(this IRenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) + internal static async Task WaitForAssertionAsync(this RenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) { using var waiter = new WaitForAssertionHelper(renderedFragment, assertion, timeout); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs index a5e002a96..e6c73d00c 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForAssertionHelper.cs @@ -26,7 +26,7 @@ public class WaitForAssertionHelper : WaitForHelper /// /// If a debugger is attached the timeout is set to , giving the possibility to debug without the timeout triggering. /// - public WaitForAssertionHelper(IRenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) + public WaitForAssertionHelper(RenderedFragment renderedFragment, Action assertion, TimeSpan? timeout = null) : base( renderedFragment, () => diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForElementHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForElementHelper.cs index 829237716..3e60fda5f 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForElementHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForElementHelper.cs @@ -15,7 +15,7 @@ internal class WaitForElementHelper : WaitForHelper /// protected override bool StopWaitingOnCheckException => false; - public WaitForElementHelper(IRenderedFragment renderedFragment, string cssSelector, TimeSpan? timeout = null) + public WaitForElementHelper(RenderedFragment renderedFragment, string cssSelector, TimeSpan? timeout = null) : base(renderedFragment, () => { var element = renderedFragment.Find(cssSelector); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForElementsHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForElementsHelper.cs index 179fdec55..dac1d6e62 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForElementsHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForElementsHelper.cs @@ -21,7 +21,7 @@ internal class WaitForElementsHelper : WaitForHelper protected override bool StopWaitingOnCheckException => true; - public WaitForElementsHelper(IRenderedFragment renderedFragment, string cssSelector, int? matchElementCount, TimeSpan? timeout = null) + public WaitForElementsHelper(RenderedFragment renderedFragment, string cssSelector, int? matchElementCount, TimeSpan? timeout = null) : base(renderedFragment, () => { var elements = renderedFragment.FindAll(cssSelector); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index 650ccccea..41537f974 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -5,7 +5,7 @@ namespace Bunit.Extensions.WaitForHelpers; /// -/// Represents a helper class that can wait for a render notifications from a type, +/// Represents a helper class that can wait for a render notifications from a type, /// until a specific timeout is reached. /// public abstract class WaitForHelper : IDisposable @@ -13,7 +13,7 @@ public abstract class WaitForHelper : IDisposable private readonly Timer timer; private readonly TaskCompletionSource checkPassedCompletionSource; private readonly Func<(bool CheckPassed, T Content)> completeChecker; - private readonly IRenderedFragment renderedFragment; + private readonly RenderedFragment renderedFragment; private readonly ILogger> logger; private readonly TestRenderer renderer; private bool isDisposed; @@ -46,7 +46,7 @@ public abstract class WaitForHelper : IDisposable /// Initializes a new instance of the class. /// protected WaitForHelper( - IRenderedFragment renderedFragment, + RenderedFragment renderedFragment, Func<(bool CheckPassed, T Content)> completeChecker, TimeSpan? timeout = null) { diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs index 4ee219c02..c07be3cc9 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForStateHelper.cs @@ -29,7 +29,7 @@ public class WaitForStateHelper : WaitForHelper /// The predicate to invoke after each render, which must returns true when the desired state has been reached. /// The maximum time to wait for the desired state. /// Thrown if the throw an exception during invocation, or if the timeout has been reached. See the inner exception for details. - public WaitForStateHelper(IRenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) + public WaitForStateHelper(RenderedFragment renderedFragment, Func statePredicate, TimeSpan? timeout = null) : base(renderedFragment, () => (statePredicate(), default), timeout) { } diff --git a/src/bunit/IRenderedComponent.cs b/src/bunit/IRenderedComponent.cs deleted file mode 100644 index 175535f1c..000000000 --- a/src/bunit/IRenderedComponent.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Bunit; - -/// -public interface IRenderedComponent : IRenderedFragment - where TComponent : IComponent -{ - /// - /// Gets the component under test. - /// - TComponent Instance { get; } -} diff --git a/src/bunit/IRenderedFragment.cs b/src/bunit/IRenderedFragment.cs deleted file mode 100644 index ebf887a3d..000000000 --- a/src/bunit/IRenderedFragment.cs +++ /dev/null @@ -1,56 +0,0 @@ -using AngleSharp.Dom; -using Bunit.Rendering; - -namespace Bunit; - -/// -/// Represents a rendered fragment. -/// -public interface IRenderedFragment : IDisposable -{ - /// - /// Gets the total number times the fragment has been through its render life-cycle. - /// - int RenderCount { get; } - - /// - /// Gets a value indicating whether the rendered component or fragment has been disposed by the . - /// - bool IsDisposed { get; } - - /// - /// Gets the id of the rendered component or fragment. - /// - int ComponentId { get; } - - /// - /// Called by the owning when it finishes a render. - /// - /// A that represents a render. - void OnRender(RenderEvent renderEvent); - - /// - /// Gets the used when rendering the component. - /// - IServiceProvider Services { get; } - - /// - /// Adds or removes an event handler that will be triggered after each render of this . - /// - event EventHandler OnAfterRender; - /// - /// An event that is raised after the markup of the is updated. - /// - event EventHandler OnMarkupUpdated; - - /// - /// Gets the HTML markup from the rendered fragment/component. - /// - string Markup { get; } - - /// - /// Gets the AngleSharp based - /// on the HTML markup from the rendered fragment/component. - /// - INodeList Nodes { get; } -} diff --git a/src/bunit/Rendering/ComponentDisposedException.cs b/src/bunit/Rendering/ComponentDisposedException.cs index 634d311f1..8784d71f2 100644 --- a/src/bunit/Rendering/ComponentDisposedException.cs +++ b/src/bunit/Rendering/ComponentDisposedException.cs @@ -1,7 +1,7 @@ namespace Bunit.Rendering; /// -/// Represents an exception that is thrown when a 's +/// Represents an exception that is thrown when a 's /// properties is accessed after the underlying component has been disposed by the renderer. /// [Serializable] diff --git a/src/bunit/Rendering/IRenderedComponentActivator.cs b/src/bunit/Rendering/IRenderedComponentActivator.cs index faf6b36dd..dceb1ff32 100644 --- a/src/bunit/Rendering/IRenderedComponentActivator.cs +++ b/src/bunit/Rendering/IRenderedComponentActivator.cs @@ -1,25 +1,25 @@ namespace Bunit.Rendering; /// -/// Represents an activator for and types. +/// Represents an activator for and types. /// public interface IRenderedComponentActivator { /// - /// Creates an with the specified . + /// Creates an with the specified . /// - IRenderedFragment CreateRenderedFragment(int componentId); + RenderedFragment CreateRenderedFragment(int componentId); /// - /// Creates an with the specified . + /// Creates an with the specified . /// - IRenderedComponent CreateRenderedComponent(int componentId) + RenderedComponent CreateRenderedComponent(int componentId) where TComponent : IComponent; /// - /// Creates an with the specified , + /// Creates an with the specified , /// , and . /// - IRenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) + RenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) where TComponent : IComponent; } diff --git a/src/bunit/Rendering/RenderEvent.cs b/src/bunit/Rendering/RenderEvent.cs index 9069cb786..eb88dac4d 100644 --- a/src/bunit/Rendering/RenderEvent.cs +++ b/src/bunit/Rendering/RenderEvent.cs @@ -20,7 +20,7 @@ public sealed class RenderEvent /// /// The to get the status for. /// A tuple of statuses indicating whether the rendered component rendered during the render cycle, if it changed or if it was disposed. - public (bool Rendered, bool Changed, bool Disposed) GetRenderStatus(IRenderedFragment renderedComponent) + public (bool Rendered, bool Changed, bool Disposed) GetRenderStatus(RenderedFragment renderedComponent) { ArgumentNullException.ThrowIfNull(renderedComponent); diff --git a/src/bunit/Rendering/RenderedComponent.cs b/src/bunit/Rendering/RenderedComponent.cs index 9ec4204a2..aa7f11f4a 100644 --- a/src/bunit/Rendering/RenderedComponent.cs +++ b/src/bunit/Rendering/RenderedComponent.cs @@ -1,15 +1,20 @@ using System.Diagnostics; +using Bunit.Rendering; -namespace Bunit.Rendering; +namespace Bunit; -/// +/// +/// Represents a rendered component. +/// [DebuggerDisplay("Component={typeof(TComponent).Name,nq},RenderCount={RenderCount}")] -internal sealed class RenderedComponent : RenderedFragment, IRenderedComponent +public sealed class RenderedComponent : RenderedFragment where TComponent : IComponent { private TComponent? instance; - /// + /// + /// Gets the component under test. + /// public TComponent Instance { get @@ -30,7 +35,8 @@ internal RenderedComponent(int componentId, TComponent instance, RenderTreeFrame UpdateMarkup(componentFrames); } - protected override void OnRender(RenderEvent renderEvent) + /// + protected override void OnRenderInternal(RenderEvent renderEvent) { // checks if this is the first render, and if it is // tries to find the TComponent in the render event diff --git a/src/bunit/Rendering/RenderedComponentActivator.cs b/src/bunit/Rendering/RenderedComponentActivator.cs index a557c2073..9b30f1418 100644 --- a/src/bunit/Rendering/RenderedComponentActivator.cs +++ b/src/bunit/Rendering/RenderedComponentActivator.cs @@ -16,16 +16,16 @@ public RenderedComponentActivator(IServiceProvider services) } /// - public IRenderedFragment CreateRenderedFragment(int componentId) + public RenderedFragment CreateRenderedFragment(int componentId) => new RenderedFragment(componentId, services); /// - public IRenderedComponent CreateRenderedComponent(int componentId) + public RenderedComponent CreateRenderedComponent(int componentId) where TComponent : IComponent => new RenderedComponent(componentId, services); /// - public IRenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) + public RenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) where TComponent : IComponent => new RenderedComponent(componentId, component, componentFrames, services); } diff --git a/src/bunit/Rendering/RenderedFragment.cs b/src/bunit/Rendering/RenderedFragment.cs index 8b5e30785..89248a674 100644 --- a/src/bunit/Rendering/RenderedFragment.cs +++ b/src/bunit/Rendering/RenderedFragment.cs @@ -1,74 +1,78 @@ using System.Diagnostics; -using AngleSharp.Diffing.Core; using AngleSharp.Dom; +using Bunit.Rendering; -namespace Bunit.Rendering; +namespace Bunit; -/// +/// +/// Represents a rendered fragment. +/// [DebuggerDisplay("Rendered:{RenderCount}")] -internal class RenderedFragment : IRenderedFragment +public class RenderedFragment : IDisposable { [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by TestServiceProvider, disposed by it.")] private readonly BunitHtmlParser htmlParser; - private readonly object markupAccessLock = new(); private string markup = string.Empty; private INodeList? latestRenderNodes; - /// + /// + /// Adds or removes an event handler that will be triggered after each render of this . + /// public event EventHandler? OnAfterRender; - /// + /// + /// An event that is raised after the markup of the is updated. + /// public event EventHandler? OnMarkupUpdated; - /// + /// + /// Gets a value indicating whether the rendered component or fragment has been disposed by the . + /// public bool IsDisposed { get; private set; } - /// + /// + /// Gets the id of the rendered component or fragment. + /// public int ComponentId { get; protected set; } - /// + /// + /// Gets the HTML markup from the rendered fragment/component. + /// public string Markup { get { EnsureComponentNotDisposed(); - - // The lock prevents a race condition between the renderers thread - // and the test frameworks thread, where one might be reading the Markup - // while the other is updating it due to async code in a rendered component. - lock (markupAccessLock) - { - // 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); - } + // 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); } } - /// + /// + /// Gets the total number times the fragment has been through its render life-cycle. + /// public int RenderCount { get; protected set; } - /// + /// + /// Gets the AngleSharp based + /// on the HTML markup from the rendered fragment/component. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] public INodeList Nodes { get { EnsureComponentNotDisposed(); - - // The lock ensures that latest nodes is always based on the latest rendered markup. - lock (markupAccessLock) - { - if (latestRenderNodes is null) - latestRenderNodes = htmlParser.Parse(Markup); - - return latestRenderNodes; - } + return latestRenderNodes ??= htmlParser.Parse(Markup); } } - /// + /// + /// Gets the used when rendering the component. + /// public IServiceProvider Services { get; } internal RenderedFragment(int componentId, IServiceProvider service) @@ -78,8 +82,14 @@ internal RenderedFragment(int componentId, IServiceProvider service) htmlParser = Services.GetRequiredService(); } - void IRenderedFragment.OnRender(RenderEvent renderEvent) + /// + /// Called by the owning when it finishes a render. + /// + /// A that represents a render. + public void OnRender(RenderEvent renderEvent) { + ArgumentNullException.ThrowIfNull(renderEvent); + if (IsDisposed) return; @@ -91,21 +101,15 @@ void IRenderedFragment.OnRender(RenderEvent renderEvent) return; } - // The lock prevents a race condition between the renderers thread - // and the test frameworks thread, where one might be reading the Markup - // while the other is updating it due to async code in a rendered component. - lock (markupAccessLock) + if (rendered) + { + OnRenderInternal(renderEvent); + RenderCount++; + } + + if (changed) { - if (rendered) - { - OnRender(renderEvent); - RenderCount++; - } - - if (changed) - { - UpdateMarkup(renderEvent.Frames); - } + UpdateMarkup(renderEvent.Frames); } // The order here is important, since consumers of the events @@ -118,25 +122,25 @@ void IRenderedFragment.OnRender(RenderEvent renderEvent) OnAfterRender?.Invoke(this, EventArgs.Empty); } + /// + /// Updates the markup of the rendered fragment. + /// protected void UpdateMarkup(RenderTreeFrameDictionary framesCollection) { - // The lock prevents a race condition between the renderers thread - // and the test frameworks thread, where one might be reading the Markup - // while the other is updating it due to async code in a rendered component. - lock (markupAccessLock) - { - latestRenderNodes = null; - var newMarkup = Htmlizer.GetHtml(ComponentId, framesCollection); - - // 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); - } + latestRenderNodes = null; + var newMarkup = Htmlizer.GetHtml(ComponentId, framesCollection); + + // 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); } - protected virtual void OnRender(RenderEvent renderEvent) { } + /// + /// Extension point for the method. + /// + protected virtual void OnRenderInternal(RenderEvent renderEvent) { } /// /// Ensures that the underlying component behind the @@ -171,5 +175,6 @@ protected virtual void Dispose(bool disposing) IsDisposed = true; markup = string.Empty; OnAfterRender = null; + OnMarkupUpdated = null; } } diff --git a/src/bunit/Rendering/TestRenderer.cs b/src/bunit/Rendering/TestRenderer.cs index 984d7434e..db7bcc508 100644 --- a/src/bunit/Rendering/TestRenderer.cs +++ b/src/bunit/Rendering/TestRenderer.cs @@ -17,7 +17,7 @@ public sealed class TestRenderer : Renderer extern static void CallSetDirectParameters(ComponentState componentState, ParameterView parameters); private readonly object renderTreeUpdateLock = new(); - private readonly Dictionary renderedComponents = new(); + private readonly Dictionary renderedComponents = new(); private readonly List rootComponents = new(); private readonly ILogger logger; private readonly IRenderedComponentActivator activator; @@ -73,11 +73,11 @@ public TestRenderer(IRenderedComponentActivator renderedComponentActivator, Test } /// - public IRenderedFragment RenderFragment(RenderFragment renderFragment) + public RenderedFragment RenderFragment(RenderFragment renderFragment) => Render(renderFragment, id => activator.CreateRenderedFragment(id)); /// - public IRenderedComponent RenderComponent(ComponentParameterCollection parameters) + public RenderedComponent RenderComponent(ComponentParameterCollection parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(parameters); @@ -143,7 +143,7 @@ public IRenderedComponent RenderComponent(ComponentParam } /// - public IRenderedComponent FindComponent(IRenderedFragment parentComponent) + public RenderedComponent FindComponent(RenderedFragment parentComponent) where TComponent : IComponent { var foundComponents = FindComponents(parentComponent, 1); @@ -153,7 +153,7 @@ public IRenderedComponent FindComponent(IRenderedFragmen } /// - public IReadOnlyList> FindComponents(IRenderedFragment parentComponent) + public IReadOnlyList> FindComponents(RenderedFragment parentComponent) where TComponent : IComponent => FindComponents(parentComponent, int.MaxValue); @@ -193,7 +193,7 @@ protected override IComponent ResolveComponentForRenderMode(Type componentType, } /// - internal Task SetDirectParametersAsync(IRenderedFragment renderedComponent, ParameterView parameters) + internal Task SetDirectParametersAsync(RenderedFragment renderedComponent, ParameterView parameters) { ObjectDisposedException.ThrowIf(disposed, this); @@ -401,7 +401,7 @@ protected override void Dispose(bool disposing) } private TResult Render(RenderFragment renderFragment, Func activator) - where TResult : IRenderedFragment + where TResult : RenderedFragment { ObjectDisposedException.ThrowIf(disposed, this); @@ -437,14 +437,14 @@ private TResult Render(RenderFragment renderFragment, Func> FindComponents(IRenderedFragment parentComponent, int resultLimit) + private List> FindComponents(RenderedFragment parentComponent, int resultLimit) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(parentComponent); ObjectDisposedException.ThrowIf(disposed, this); - var result = new List>(); + var result = new List>(); var framesCollection = new RenderTreeFrameDictionary(); // Blocks the renderer from changing the render tree @@ -484,12 +484,12 @@ void FindComponentsInRenderTree(int componentId) } } - private IRenderedComponent GetOrCreateRenderedComponent(RenderTreeFrameDictionary framesCollection, int componentId, TComponent component) + private RenderedComponent GetOrCreateRenderedComponent(RenderTreeFrameDictionary framesCollection, int componentId, TComponent component) where TComponent : IComponent { if (renderedComponents.TryGetValue(componentId, out var renderedComponent)) { - return (IRenderedComponent)renderedComponent; + return (RenderedComponent)renderedComponent; } LoadRenderTreeFrames(componentId, framesCollection); diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 47d492202..0b2eb1363 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -13,7 +13,7 @@ public class TestContext : IDisposable private TestRenderer? testRenderer; /// - /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . + /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . /// /// The default is 1 second. public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); @@ -123,7 +123,7 @@ public void DisposeComponents() /// Type of the component to render. /// Parameters to pass to the component when it is rendered. /// The rendered . - public virtual IRenderedComponent RenderComponent(params ComponentParameter[] parameters) + public virtual RenderedComponent RenderComponent(params ComponentParameter[] parameters) where TComponent : IComponent { var renderFragment = new ComponentParameterCollection { parameters } @@ -138,7 +138,7 @@ public virtual IRenderedComponent RenderComponent(params /// Type of the component to render. /// The ComponentParameterBuilder action to add type safe parameters to pass to the component when it is rendered. /// The rendered . - public virtual IRenderedComponent RenderComponent(Action>? parameterBuilder = null) + public virtual RenderedComponent RenderComponent(Action>? parameterBuilder = null) where TComponent : IComponent { var renderFragment = new ComponentParameterCollectionBuilder(parameterBuilder) @@ -156,17 +156,17 @@ public virtual IRenderedComponent RenderComponent(Action /// /// The type of component to find in the render tree. /// The render fragment to render. - /// The . - public virtual IRenderedComponent Render(RenderFragment renderFragment) + /// The . + public virtual RenderedComponent Render(RenderFragment renderFragment) where TComponent : IComponent => this.RenderInsideRenderTree(renderFragment); /// - /// Renders the and returns it as a . + /// Renders the and returns it as a . /// /// The render fragment to render. - /// The . - public virtual IRenderedFragment Render(RenderFragment renderFragment) + /// The . + public virtual RenderedFragment Render(RenderFragment renderFragment) => this.RenderInsideRenderTree(renderFragment); /// diff --git a/src/bunit/TestContextWrapper.cs b/src/bunit/TestContextWrapper.cs index 8afa6b4f8..c8f6757d1 100644 --- a/src/bunit/TestContextWrapper.cs +++ b/src/bunit/TestContextWrapper.cs @@ -43,7 +43,7 @@ public abstract class TestContextWrapper /// Type of the component to render. /// Parameters to pass to the component when it is rendered. /// The rendered . - public virtual IRenderedComponent RenderComponent(params ComponentParameter[] parameters) + public virtual RenderedComponent RenderComponent(params ComponentParameter[] parameters) where TComponent : IComponent => TestContext?.RenderComponent(parameters) ?? throw new InvalidOperationException("The TestContext has not been initialized."); @@ -53,7 +53,7 @@ public virtual IRenderedComponent RenderComponent(params /// Type of the component to render. /// The ComponentParameterBuilder action to add type safe parameters to pass to the component when it is rendered. /// The rendered . - public virtual IRenderedComponent RenderComponent(Action> parameterBuilder) + public virtual RenderedComponent RenderComponent(Action> parameterBuilder) where TComponent : IComponent => TestContext?.RenderComponent(parameterBuilder) ?? throw new InvalidOperationException("The TestContext has not been initialized."); @@ -65,17 +65,17 @@ public virtual IRenderedComponent RenderComponent(Action /// /// The type of component to find in the render tree. /// The render fragment to render. - /// The . - public virtual IRenderedComponent Render(RenderFragment renderFragment) + /// The . + public virtual RenderedComponent Render(RenderFragment renderFragment) where TComponent : IComponent => TestContext?.Render(renderFragment) ?? throw new InvalidOperationException("The TestContext has not been initialized."); /// - /// Renders the and returns it as a . + /// Renders the and returns it as a . /// /// The render fragment to render. - /// The . - public virtual IRenderedFragment Render(RenderFragment renderFragment) + /// The . + public virtual RenderedFragment Render(RenderFragment renderFragment) => TestContext?.Render(renderFragment) ?? throw new InvalidOperationException("The TestContext has not been initialized."); /// diff --git a/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs index 242e3ed4c..e813f10b5 100644 --- a/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs +++ b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs @@ -23,8 +23,8 @@ public static IEnumerable GetCompareToMethods() object p1 = p1Info.ParameterType.ToMockInstance(); object p2 = p2Info.ParameterType.ToMockInstance(); - yield return new object[] { method, p1Info.Name!, new[] { null!, p2! } }; - yield return new object[] { method, p2Info.Name!, new[] { p1!, null! } }; + yield return [method, p1Info.Name!, new[] { null!, p2! }]; + yield return [method, p2Info.Name!, new[] { p1!, null! }]; } } diff --git a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs index 99d7706af..4b038e676 100644 --- a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs +++ b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs @@ -8,8 +8,8 @@ public partial class MarkupMatchesAssertExtensionsTest : TestContext private const string ExpectedMarkup = "
    BAR
    "; private static readonly RenderFragment ActualRenderFragment = b => b.AddMarkupContent(0, ActualMarkup); private static readonly RenderFragment ExpectedRenderFragment = b => b.AddMarkupContent(0, ExpectedMarkup); - private IRenderedFragment ActualRenderedFragment => Render(ActualRenderFragment); - private IRenderedFragment ExpectedRenderedFragment => Render(ExpectedRenderFragment); + private RenderedFragment ActualRenderedFragment => Render(ActualRenderFragment); + private RenderedFragment ExpectedRenderedFragment => Render(ExpectedRenderFragment); private INodeList ActualNodeList => ActualRenderedFragment.Nodes; private INodeList ExpectedNodeList => ExpectedRenderedFragment.Nodes; private INode ActualNode => ActualNodeList[0]; @@ -23,8 +23,8 @@ public void Test001() Should.Throw(() => default(string)!.MarkupMatches(default(string)!)); Should.Throw(() => default(string)!.MarkupMatches(ExpectedRenderedFragment)); - Should.Throw(() => ActualMarkup.MarkupMatches(default(IRenderedFragment)!)); - Should.Throw(() => default(string)!.MarkupMatches(default(IRenderedFragment)!)); + Should.Throw(() => ActualMarkup.MarkupMatches(default(RenderedFragment)!)); + Should.Throw(() => default(string)!.MarkupMatches(default(RenderedFragment)!)); Should.Throw(() => default(string)!.MarkupMatches(ExpectedNodeList)); Should.Throw(() => ActualMarkup.MarkupMatches(default(INodeList)!)); @@ -42,9 +42,9 @@ public void Test001() Should.Throw(() => ActualNode.MarkupMatches(default(INodeList)!)); Should.Throw(() => default(INode)!.MarkupMatches(default(INodeList)!)); - Should.Throw(() => default(IRenderedFragment)!.MarkupMatches(ExpectedRenderFragment)); + Should.Throw(() => default(RenderedFragment)!.MarkupMatches(ExpectedRenderFragment)); Should.Throw(() => ActualRenderedFragment.MarkupMatches(default(RenderFragment)!)); - Should.Throw(() => default(IRenderedFragment)!.MarkupMatches(default(RenderFragment)!)); + Should.Throw(() => default(RenderedFragment)!.MarkupMatches(default(RenderFragment)!)); Should.Throw(() => default(INode)!.MarkupMatches(ExpectedRenderFragment)); Should.Throw(() => ActualNode.MarkupMatches(default(RenderFragment)!)); @@ -59,7 +59,7 @@ public void Test001() public void Test002() => Should.Throw(() => ActualMarkup.MarkupMatches(ExpectedMarkup)); - [Fact(DisplayName = "MarkupMatches(string, IRenderedFragment) correctly diffs markup")] + [Fact(DisplayName = "MarkupMatches(string, RenderedFragment) correctly diffs markup")] public void Test003() => Should.Throw(() => ActualMarkup.MarkupMatches(ExpectedRenderedFragment)); @@ -79,7 +79,7 @@ public void Test006() public void Test007() => Should.Throw(() => ActualNode.MarkupMatches(ExpectedNodeList)); - [Fact(DisplayName = "MarkupMatches(IRenderedFragment, RenderFragment) correctly diffs markup")] + [Fact(DisplayName = "MarkupMatches(RenderedFragment, RenderFragment) correctly diffs markup")] public void Test008() => Should.Throw(() => ActualRenderedFragment.MarkupMatches(ExpectedRenderFragment)); @@ -91,10 +91,10 @@ public void Test009() public void Test0010() => Should.Throw(() => ActualNodeList.MarkupMatches(ExpectedRenderFragment)); - private IRenderedFragment FindAllRenderedFragment => Render(b => b.AddMarkupContent(0, "

    test

    ")); + private RenderedFragment FindAllRenderedFragment => Render(b => b.AddMarkupContent(0, "

    test

    ")); private readonly string findAllExpectedRenderFragment = "

    test

    "; - [Fact(DisplayName = "MarkupMatches combination works with IRenderedFragment's FindAll extension method")] + [Fact(DisplayName = "MarkupMatches combination works with RenderedFragment's FindAll extension method")] public void Test011() { FindAllRenderedFragment.FindAll("p").MarkupMatches(findAllExpectedRenderFragment); @@ -151,4 +151,4 @@ public void Test016() cut.MarkupMatches(expectedMarkup); } -} \ No newline at end of file +} diff --git a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs index 77a60513d..bc8f6409f 100644 --- a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs +++ b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs @@ -37,12 +37,12 @@ private async Task VerifyEventCallbackAsync(string expectedName) EventCallbackCalled.ShouldBeTrue(); } - private IRenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) + private RenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) { return Renderer.RenderFragment(renderFragment); } - private IRenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) + private RenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) where TComponent : IComponent { var res = Renderer.RenderFragment(renderFragment); @@ -695,16 +695,16 @@ public void Test314() action.ShouldNotThrow(); } - + [Fact(DisplayName = "Supplying query string should be reflected in component parameter")] public void Test315() { var navigationManager = Services.GetRequiredService(); var uri = navigationManager.GetUriWithQueryParameter("Query", "Test"); navigationManager.NavigateTo(uri); - + var cut = RenderComponent(); - + cut.Instance.Query.ShouldBe("Test"); } @@ -719,7 +719,7 @@ public void Test316() .ShouldBe(""" To pass a value to a SupplyParameterFromQuery parameter, use the NavigationManager and navigate to the URI. For example: - + var uri = NavigationManager.GetUriWithQueryParameter("Query", "Foo"); NavigationManager.NavigateTo(uri); """); @@ -801,7 +801,7 @@ private sealed class ValidNamesComponent : ComponentBase [Parameter] public Expression> FacialExpressionExpression { get; set; } } #pragma warning restore S1144 // Unused private types or members should be removed - + private sealed class SupplyFromQueryParameterComponent : ComponentBase { [SupplyParameterFromQuery] public string Query { get; set; } diff --git a/tests/bunit.tests/ComponentParameterCollectionTest.cs b/tests/bunit.tests/ComponentParameterCollectionTest.cs index 99b0250b6..b091b364d 100644 --- a/tests/bunit.tests/ComponentParameterCollectionTest.cs +++ b/tests/bunit.tests/ComponentParameterCollectionTest.cs @@ -2,7 +2,7 @@ namespace Bunit; public class ComponentParameterCollectionTest : TestContext { - private IRenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) + private RenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) { var res = Renderer.RenderFragment(renderFragment); return res.FindComponent(); diff --git a/tests/bunit.tests/ComponentParameterFactoryTest.cs b/tests/bunit.tests/ComponentParameterFactoryTest.cs index d3dc660d5..0f7d65adb 100644 --- a/tests/bunit.tests/ComponentParameterFactoryTest.cs +++ b/tests/bunit.tests/ComponentParameterFactoryTest.cs @@ -8,7 +8,7 @@ public class ComponentParameterFactoryTest private const string EXPECTED = nameof(EXPECTED); private static readonly TestContext Context = new(); - private static IRenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) + private static RenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) { return Context.Renderer.RenderFragment(renderFragment); } diff --git a/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs b/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs index b8b83b0c5..20473eabd 100644 --- a/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs +++ b/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs @@ -5,13 +5,13 @@ namespace Bunit; public class TriggerEventSpy where TEventArgs : EventArgs, new() { - private readonly IRenderedComponent> renderedComponent; + private readonly RenderedComponent> renderedComponent; private readonly string element; private TEventArgs? receivedEvent; public TEventArgs RaisedEvent => receivedEvent!; - public TriggerEventSpy(Func>> componentRenderer, string element, string eventName) + public TriggerEventSpy(Func>> componentRenderer, string element, string eventName) { ArgumentNullException.ThrowIfNull(componentRenderer); diff --git a/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs b/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs index 44b418f7c..31d40f0ad 100644 --- a/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs +++ b/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs @@ -60,7 +60,7 @@ public void Test003() [Fact(DisplayName = "UploadFile throws exception when InputFile is null")] public void Test004() { - Action action = () => ((IRenderedComponent)null).UploadFiles(); + Action action = () => ((RenderedComponent)null).UploadFiles(); action.ShouldThrow(); } diff --git a/tests/bunit.tests/Rendering/TestRendererTest.cs b/tests/bunit.tests/Rendering/TestRendererTest.cs index a4e1ecf2f..b9fb6a491 100644 --- a/tests/bunit.tests/Rendering/TestRendererTest.cs +++ b/tests/bunit.tests/Rendering/TestRendererTest.cs @@ -186,7 +186,7 @@ public void Test030() // act var childCuts = sut.FindComponents(cut) - .OfType>() + .OfType>() .ToList(); // assert diff --git a/tests/bunit.tests/TestUtilities/MockingHelpers.cs b/tests/bunit.tests/TestUtilities/MockingHelpers.cs index 2ba25ca7a..399a8c4dd 100644 --- a/tests/bunit.tests/TestUtilities/MockingHelpers.cs +++ b/tests/bunit.tests/TestUtilities/MockingHelpers.cs @@ -1,3 +1,5 @@ +using Bunit.Rendering; + namespace Bunit.TestUtilities; /// @@ -16,6 +18,11 @@ public static class MockingHelpers public static object ToMockInstance(this Type type) { ArgumentNullException.ThrowIfNull(type); + + if (type == typeof(RenderedFragment)) + { + return new RenderedFragmentFake(); + } if (type.IsMockable()) { @@ -45,4 +52,19 @@ public static bool IsMockable(this Type type) /// Gets whether a type is a delegate type. /// public static bool IsDelegateType(this Type type) => type == DelegateType; + + private sealed class RenderedFragmentFake : RenderedFragment + { + public RenderedFragmentFake() : base(0, Fake()) + { + } + + private static IServiceProvider Fake() + { + using var instance = new BunitHtmlParser(); + var fake = Substitute.For(); + fake.GetService(typeof(BunitHtmlParser)).Returns(instance); + return fake; + } + } } From 67d51f31d15c44146c9d2972d18e79f333a3e098 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 11:41:02 +0100 Subject: [PATCH 012/100] refactor: Renamed TestRenderer to BunitRenderer --- .../MarkupMatchesAssertExtensions.cs | 2 +- src/bunit/Diffing/HtmlComparer.cs | 2 +- .../TriggerEventDispatchExtensions.cs | 10 +-- ...tensions.cs => BunitRendererExtensions.cs} | 8 +- .../RenderedFragmentInvokeAsyncExtensions.cs | 8 +- .../WaitForHelpers/WaitForHelper.cs | 2 +- src/bunit/Rendering/BunitHtmlParser.cs | 2 +- .../{TestRenderer.cs => BunitRenderer.cs} | 80 ++++++++++++++----- ...ns.cs => BunitRendererLoggerExtensions.cs} | 18 ++--- src/bunit/Rendering/RenderEvent.cs | 2 +- src/bunit/Rendering/RenderedFragment.cs | 4 +- src/bunit/TestContext.cs | 14 ++-- src/bunit/TestContextWrapper.cs | 2 +- .../BunitPersistentComponentState.cs | 4 +- ...tRendererTest.cs => BunitRendererBunit.cs} | 24 +++++- .../Rendering/TestRendererTest.net5.cs | 24 ------ 16 files changed, 118 insertions(+), 88 deletions(-) rename src/bunit/Extensions/{TestRendererExtensions.cs => BunitRendererExtensions.cs} (89%) rename src/bunit/Rendering/{TestRenderer.cs => BunitRenderer.cs} (79%) rename src/bunit/Rendering/{TestRendererLoggerExtensions.cs => BunitRendererLoggerExtensions.cs} (84%) rename tests/bunit.tests/Rendering/{TestRendererTest.cs => BunitRendererBunit.cs} (95%) delete mode 100644 tests/bunit.tests/Rendering/TestRendererTest.net5.cs diff --git a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs index 8f61e9477..4bb3fc51b 100644 --- a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs +++ b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs @@ -274,7 +274,7 @@ public static void MarkupMatches(this RenderedFragment actual, RenderFragment ex // TODO: This will be obsolete with: https://github.com/bUnit-dev/bUnit/issues/1018 // As the renderer would be transient we don't have to new up an instance - using var renderer = new TestRenderer( + using var renderer = new BunitRenderer( actual.Services.GetRequiredService(), actual.Services.GetRequiredService(), actual.Services.GetRequiredService()); diff --git a/src/bunit/Diffing/HtmlComparer.cs b/src/bunit/Diffing/HtmlComparer.cs index 2dd73d112..9fc2180bc 100644 --- a/src/bunit/Diffing/HtmlComparer.cs +++ b/src/bunit/Diffing/HtmlComparer.cs @@ -8,7 +8,7 @@ namespace Bunit.Diffing; /// -/// Represents a test HTML comparer, that is configured to work with markup generated by the and classes. +/// Represents a test HTML comparer, that is configured to work with markup generated by the and classes. /// public sealed class HtmlComparer { diff --git a/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs index 62e44e9a1..7d75c7f6f 100644 --- a/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs +++ b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs @@ -63,7 +63,7 @@ public static Task TriggerEventAsync(this IElement element, string eventName, Ev ArgumentNullException.ThrowIfNull(eventName); var renderer = element.GetTestContext()?.Renderer - ?? throw new InvalidOperationException($"Blazor events can only be raised on elements rendered with the Blazor test renderer '{nameof(TestRenderer)}'."); + ?? throw new InvalidOperationException($"Blazor events can only be raised on elements rendered with the Blazor test renderer '{nameof(BunitRenderer)}'."); // TriggerEventsAsync will traverse the DOM tree to find // all event handlers that needs to be triggered. This is done @@ -78,7 +78,7 @@ public static Task TriggerEventAsync(this IElement element, string eventName, Ev } [SuppressMessage("Globalization", "CA1308:Normalize strings to uppercase", Justification = "HTML events are standardize to lower case and safe in this context.")] - private static Task TriggerEventsAsync(TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) + private static Task TriggerEventsAsync(BunitRenderer renderer, IElement element, string eventName, EventArgs eventArgs) { var isNonBubblingEvent = NonBubblingEvents.Contains(eventName.ToLowerInvariant()); var unwrappedElement = element.Unwrap(); @@ -88,7 +88,7 @@ private static Task TriggerEventsAsync(TestRenderer renderer, IElement element, : TriggerBubblingEventAsync(renderer, unwrappedElement, eventName, eventArgs); } - private static Task TriggerNonBubblingEventAsync(TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) + private static Task TriggerNonBubblingEventAsync(BunitRenderer renderer, IElement element, string eventName, EventArgs eventArgs) { var eventAttrName = Htmlizer.ToBlazorAttribute(eventName); @@ -105,7 +105,7 @@ private static Task TriggerNonBubblingEventAsync(TestRenderer renderer, IElement throw new MissingEventHandlerException(element, eventName); } - private static Task TriggerBubblingEventAsync(TestRenderer renderer, IElement element, string eventName, EventArgs eventArgs) + private static Task TriggerBubblingEventAsync(BunitRenderer renderer, IElement element, string eventName, EventArgs eventArgs) { var eventTasks = GetDispatchEventTasks(renderer, element, eventName, eventArgs); @@ -118,7 +118,7 @@ private static Task TriggerBubblingEventAsync(TestRenderer renderer, IElement el } private static List GetDispatchEventTasks( - TestRenderer renderer, + BunitRenderer renderer, IElement element, string eventName, EventArgs eventArgs) diff --git a/src/bunit/Extensions/TestRendererExtensions.cs b/src/bunit/Extensions/BunitRendererExtensions.cs similarity index 89% rename from src/bunit/Extensions/TestRendererExtensions.cs rename to src/bunit/Extensions/BunitRendererExtensions.cs index 31d9817f7..d8c7c097c 100644 --- a/src/bunit/Extensions/TestRendererExtensions.cs +++ b/src/bunit/Extensions/BunitRendererExtensions.cs @@ -3,10 +3,10 @@ namespace Bunit.Extensions; /// -/// Helper methods that make it easier to work directly with a +/// Helper methods that make it easier to work directly with a /// in bUnit web. /// -public static class TestRendererExtensions +public static class BunitRendererExtensions { /// /// Renders a with the parameters passed to it. @@ -15,7 +15,7 @@ public static class TestRendererExtensions /// The renderer to use. /// The parameters to pass to the component. /// A that provides access to the rendered component. - public static RenderedComponent RenderComponent(this TestRenderer renderer, params ComponentParameter[] parameters) + public static RenderedComponent RenderComponent(this BunitRenderer renderer, params ComponentParameter[] parameters) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); @@ -34,7 +34,7 @@ public static RenderedComponent RenderComponent(this Tes /// The renderer to use. /// The a builder to create parameters to pass to the component. /// A that provides access to the rendered component. - public static RenderedComponent RenderComponent(this TestRenderer renderer, Action> parameterBuilder) + public static RenderedComponent RenderComponent(this BunitRenderer renderer, Action> parameterBuilder) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); diff --git a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index 232eaa875..cac702a71 100644 --- a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -8,7 +8,7 @@ namespace Bunit; public static class RenderedFragmentInvokeAsyncExtensions { /// - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered fragment whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. @@ -26,7 +26,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Action wo } /// - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. @@ -44,7 +44,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Func - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. @@ -62,7 +62,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Fun } /// - /// Invokes the given in the context of the associated . + /// Invokes the given in the context of the associated . /// /// The rendered component whose dispatcher to invoke with. /// The work item to execute on the renderer's thread. diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index 41537f974..feee65844 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -15,7 +15,7 @@ public abstract class WaitForHelper : IDisposable private readonly Func<(bool CheckPassed, T Content)> completeChecker; private readonly RenderedFragment renderedFragment; private readonly ILogger> logger; - private readonly TestRenderer renderer; + private readonly BunitRenderer renderer; private bool isDisposed; private int checkCount; private Exception? capturedException; diff --git a/src/bunit/Rendering/BunitHtmlParser.cs b/src/bunit/Rendering/BunitHtmlParser.cs index c44abab7f..261c8a5ba 100644 --- a/src/bunit/Rendering/BunitHtmlParser.cs +++ b/src/bunit/Rendering/BunitHtmlParser.cs @@ -25,7 +25,7 @@ public sealed class BunitHtmlParser : IDisposable /// /// Initializes a new instance of the class - /// with a AngleSharp context without a registered. + /// with a AngleSharp context without a registered. /// public BunitHtmlParser() : this(Configuration.Default.WithCss().With(new HtmlComparer())) { } diff --git a/src/bunit/Rendering/TestRenderer.cs b/src/bunit/Rendering/BunitRenderer.cs similarity index 79% rename from src/bunit/Rendering/TestRenderer.cs rename to src/bunit/Rendering/BunitRenderer.cs index db7bcc508..c52d0e24a 100644 --- a/src/bunit/Rendering/TestRenderer.cs +++ b/src/bunit/Rendering/BunitRenderer.cs @@ -6,20 +6,20 @@ namespace Bunit.Rendering; /// -/// Represents a bUnit used to render Blazor components and fragments during bUnit tests. +/// Represents a bUnit used to render Blazor components and fragments during bUnit tests. /// -public sealed class TestRenderer : Renderer +public sealed class BunitRenderer : Renderer { [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")] - extern static ref bool GetIsBatchInProgressField(Renderer renderer); + private static extern ref bool GetIsBatchInProgressField(Renderer renderer); [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "SetDirectParameters")] - extern static void CallSetDirectParameters(ComponentState componentState, ParameterView parameters); + private static extern void CallSetDirectParameters(ComponentState componentState, ParameterView parameters); private readonly object renderTreeUpdateLock = new(); private readonly Dictionary renderedComponents = new(); private readonly List rootComponents = new(); - private readonly ILogger logger; + private readonly ILogger logger; private readonly IRenderedComponentActivator activator; private bool disposed; private TaskCompletionSource unhandledExceptionTsc = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -39,7 +39,10 @@ private bool IsBatchInProgress } } - /// + /// + /// Gets a , which completes when an unhandled exception + /// is thrown during the rendering of a component, that is caught by the renderer. + /// public Task UnhandledException => unhandledExceptionTsc.Task; /// @@ -51,32 +54,41 @@ private bool IsBatchInProgress internal int RenderCount { get; private set; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public TestRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory) + public BunitRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory) : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), null)) { - logger = loggerFactory.CreateLogger(); + logger = loggerFactory.CreateLogger(); activator = renderedComponentActivator; ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - public TestRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) + public BunitRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), componentActivator)) { - logger = loggerFactory.CreateLogger(); + logger = loggerFactory.CreateLogger(); activator = renderedComponentActivator; ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } - /// + /// + /// Renders the . + /// + /// The to render. + /// A that provides access to the rendered . public RenderedFragment RenderFragment(RenderFragment renderFragment) => Render(renderFragment, id => activator.CreateRenderedFragment(id)); - /// + /// + /// Renders a with the passed to it. + /// + /// The type of component to render. + /// The parameters to pass to the component. + /// A that provides access to the rendered component. public RenderedComponent RenderComponent(ComponentParameterCollection parameters) where TComponent : IComponent { @@ -86,14 +98,26 @@ public RenderedComponent RenderComponent(ComponentParame return Render(renderFragment, id => activator.CreateRenderedComponent(id)); } - /// + /// + /// Notifies the renderer that an event has occurred. + /// + /// The value from the original event attribute. + /// Information that the renderer can use to update the state of the existing render tree to match the UI. + /// Arguments to be passed to the event handler. + /// A which will complete once all asynchronous processing related to the event has completed. public new Task DispatchEventAsync( ulong eventHandlerId, EventFieldInfo fieldInfo, EventArgs eventArgs) => DispatchEventAsync(eventHandlerId, fieldInfo, eventArgs, ignoreUnknownEventHandlers: false); - /// - /// + /// + /// Notifies the renderer that an event has occurred. + /// + /// The value from the original event attribute. + /// Information that the renderer can use to update the state of the existing render tree to match the UI. + /// Arguments to be passed to the event handler. + /// Set to true to ignore the . + /// A which will complete once all asynchronous processing related to the event has completed. public new Task DispatchEventAsync( ulong eventHandlerId, EventFieldInfo fieldInfo, @@ -142,7 +166,11 @@ public RenderedComponent RenderComponent(ComponentParame } } - /// + /// + /// Performs a depth-first search for the first child component of the . + /// + /// Type of component to find. + /// Parent component to search. public RenderedComponent FindComponent(RenderedFragment parentComponent) where TComponent : IComponent { @@ -152,12 +180,18 @@ public RenderedComponent FindComponent(RenderedFragment : throw new ComponentNotFoundException(typeof(TComponent)); } - /// + /// + /// Performs a depth-first search for all child components of the . + /// + /// Type of components to find. + /// Parent component to search. public IReadOnlyList> FindComponents(RenderedFragment parentComponent) where TComponent : IComponent => FindComponents(parentComponent, int.MaxValue); - /// + /// + /// Disposes all components rendered by the . + /// public void DisposeComponents() { ObjectDisposedException.ThrowIf(disposed, this); @@ -225,7 +259,7 @@ internal Task SetDirectParametersAsync(RenderedFragment renderedComponent, Param return result; - static void SetDirectParametersViaComponentState(TestRenderer renderer, int componentId, in ParameterView parameters) + static void SetDirectParametersViaComponentState(BunitRenderer renderer, int componentId, in ParameterView parameters) { var componentState = renderer.GetComponentState(componentId); CallSetDirectParameters(componentState, parameters); @@ -534,8 +568,10 @@ private ArrayRange GetOrLoadRenderTreeFrame(RenderTreeFrameDict } /// - protected override void HandleException([NotNull] Exception exception) + protected override void HandleException(Exception exception) { + ArgumentNullException.ThrowIfNull(exception); + if (disposed) return; diff --git a/src/bunit/Rendering/TestRendererLoggerExtensions.cs b/src/bunit/Rendering/BunitRendererLoggerExtensions.cs similarity index 84% rename from src/bunit/Rendering/TestRendererLoggerExtensions.cs rename to src/bunit/Rendering/BunitRendererLoggerExtensions.cs index 1960677f9..364641309 100644 --- a/src/bunit/Rendering/TestRendererLoggerExtensions.cs +++ b/src/bunit/Rendering/BunitRendererLoggerExtensions.cs @@ -3,7 +3,7 @@ namespace Bunit.Rendering; -internal static class TestRendererLoggerExtensions +internal static class BunitRendererLoggerExtensions { private static readonly Action ComponentDisposed = LoggerMessage.Define( @@ -11,7 +11,7 @@ internal static class TestRendererLoggerExtensions new EventId(11, "ComponentDisposed"), "Component {Id} has been disposed."); - internal static void LogComponentDisposed(this ILogger logger, int componentId) + internal static void LogComponentDisposed(this ILogger logger, int componentId) { if (logger.IsEnabled(LogLevel.Debug)) { @@ -25,7 +25,7 @@ internal static void LogComponentDisposed(this ILogger logger, int new EventId(12, "ComponentRendered"), "Component {ComponentId} has been rendered."); - internal static void LogComponentRendered(this ILogger logger, int componentId) + internal static void LogComponentRendered(this ILogger logger, int componentId) { if (logger.IsEnabled(LogLevel.Debug)) { @@ -39,7 +39,7 @@ internal static void LogComponentRendered(this ILogger logger, int new EventId(14, "DisposedChildInRenderTreeFrame"), "A parent components {ParentComponentId} has a disposed component {ComponentId} as its child."); - internal static void LogDisposedChildInRenderTreeFrame(this ILogger logger, int parentComponentId, int componentId) + internal static void LogDisposedChildInRenderTreeFrame(this ILogger logger, int parentComponentId, int componentId) { if (logger.IsEnabled(LogLevel.Warning)) { @@ -53,7 +53,7 @@ internal static void LogDisposedChildInRenderTreeFrame(this ILogger logger) + internal static void LogAsyncInitialRender(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { @@ -67,7 +67,7 @@ internal static void LogAsyncInitialRender(this ILogger logger) new EventId(21, "InitialRenderCompleted"), "The initial render of component {ComponentId} is completed."); - internal static void LogInitialRenderCompleted(this ILogger logger, int componentId) + internal static void LogInitialRenderCompleted(this ILogger logger, int componentId) { if (logger.IsEnabled(LogLevel.Debug)) { @@ -81,7 +81,7 @@ private static readonly Action UnhandledExce new EventId(30, "UnhandledException"), "An unhandled exception happened during rendering: {Message}" + Environment.NewLine + "{StackTrace}"); - internal static void LogUnhandledException(this ILogger logger, Exception exception) + internal static void LogUnhandledException(this ILogger logger, Exception exception) { if (logger.IsEnabled(LogLevel.Error)) { @@ -95,7 +95,7 @@ internal static void LogUnhandledException(this ILogger logger, Ex new EventId(31, "RenderCycleActiveAfterDispose"), "A component attempted to update the render tree after the renderer was disposed."); - internal static void LogRenderCycleActiveAfterDispose(this ILogger logger) + internal static void LogRenderCycleActiveAfterDispose(this ILogger logger) { if (logger.IsEnabled(LogLevel.Warning)) { @@ -115,7 +115,7 @@ internal static void LogRenderCycleActiveAfterDispose(this ILogger new EventId(40, "DispatchingEvent"), "Dispatching {EventArgs} to handler (id = {EventHandlerId}) on component {ComponentId}."); - internal static void LogDispatchingEvent(this ILogger logger, ulong eventHandlerId, EventFieldInfo fieldInfo, EventArgs eventArgs) + internal static void LogDispatchingEvent(this ILogger logger, ulong eventHandlerId, EventFieldInfo fieldInfo, EventArgs eventArgs) { if (logger.IsEnabled(LogLevel.Debug)) { diff --git a/src/bunit/Rendering/RenderEvent.cs b/src/bunit/Rendering/RenderEvent.cs index eb88dac4d..e550a4f6f 100644 --- a/src/bunit/Rendering/RenderEvent.cs +++ b/src/bunit/Rendering/RenderEvent.cs @@ -1,7 +1,7 @@ namespace Bunit.Rendering; /// -/// Represents an render event from a . +/// Represents an render event from a . /// public sealed class RenderEvent { diff --git a/src/bunit/Rendering/RenderedFragment.cs b/src/bunit/Rendering/RenderedFragment.cs index 89248a674..dc7efbeb0 100644 --- a/src/bunit/Rendering/RenderedFragment.cs +++ b/src/bunit/Rendering/RenderedFragment.cs @@ -26,7 +26,7 @@ public class RenderedFragment : IDisposable public event EventHandler? OnMarkupUpdated; /// - /// Gets a value indicating whether the rendered component or fragment has been disposed by the . + /// Gets a value indicating whether the rendered component or fragment has been disposed by the . /// public bool IsDisposed { get; private set; } @@ -83,7 +83,7 @@ internal RenderedFragment(int componentId, IServiceProvider service) } /// - /// Called by the owning when it finishes a render. + /// Called by the owning when it finishes a render. /// /// A that represents a render. public void OnRender(RenderEvent renderEvent) diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 0b2eb1363..1a2342214 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -10,7 +10,7 @@ namespace Bunit; public class TestContext : IDisposable { private bool disposed; - private TestRenderer? testRenderer; + private BunitRenderer? bunitRenderer; /// /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . @@ -21,7 +21,7 @@ public class TestContext : IDisposable /// /// Gets the renderer used by the test context. /// - public TestRenderer Renderer => testRenderer ??= CreateTestRenderer(); + public BunitRenderer Renderer => bunitRenderer ??= CreateRenderer(); /// /// Gets bUnits JSInterop, that allows setting up handlers for invocations @@ -91,7 +91,7 @@ protected virtual void Dispose(bool disposing) // Ensure the renderer is disposed before all others, // otherwise a render cycle may be ongoing and try to access // the service provider to perform operations. - if (testRenderer is IDisposable renderer) + if (bunitRenderer is IDisposable renderer) { renderer.Dispose(); } @@ -173,16 +173,16 @@ public virtual RenderedFragment Render(RenderFragment renderFragment) /// Dummy method required to allow Blazor's compiler to generate /// C# from .razor files. /// - protected virtual void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { } + protected virtual void BuildRenderTree(RenderTreeBuilder builder) { } - private TestRenderer CreateTestRenderer() + private BunitRenderer CreateRenderer() { var renderedComponentActivator = Services.GetRequiredService(); var logger = Services.GetRequiredService(); var componentActivator = Services.GetService(); return componentActivator is null - ? new TestRenderer(renderedComponentActivator, Services, logger) - : new TestRenderer(renderedComponentActivator, Services, logger, componentActivator); + ? new BunitRenderer(renderedComponentActivator, Services, logger) + : new BunitRenderer(renderedComponentActivator, Services, logger, componentActivator); } } diff --git a/src/bunit/TestContextWrapper.cs b/src/bunit/TestContextWrapper.cs index c8f6757d1..937ef66d6 100644 --- a/src/bunit/TestContextWrapper.cs +++ b/src/bunit/TestContextWrapper.cs @@ -17,7 +17,7 @@ public abstract class TestContextWrapper /// /// Gets the renderer used by the test context. /// - public TestRenderer Renderer => TestContext?.Renderer ?? throw new InvalidOperationException("The TestContext has not been initialized."); + public BunitRenderer Renderer => TestContext?.Renderer ?? throw new InvalidOperationException("The TestContext has not been initialized."); /// /// Gets the service collection and service provider that is used when a diff --git a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs index ae8b12f58..1209e5231 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs @@ -17,7 +17,7 @@ public sealed class BunitPersistentComponentState }; private readonly BunitPersistentComponentStateStore store; private readonly Lazy manager; - private readonly Lazy renderer; + private readonly Lazy renderer; /// /// Initializes a new instance of the class. @@ -27,7 +27,7 @@ internal BunitPersistentComponentState(IServiceProvider services) { store = new BunitPersistentComponentStateStore(); manager = new Lazy(() => services.GetRequiredService()); - renderer = new Lazy(() => services.GetRequiredService().Renderer); + renderer = new Lazy(() => services.GetRequiredService().Renderer); } /// diff --git a/tests/bunit.tests/Rendering/TestRendererTest.cs b/tests/bunit.tests/Rendering/BunitRendererBunit.cs similarity index 95% rename from tests/bunit.tests/Rendering/TestRendererTest.cs rename to tests/bunit.tests/Rendering/BunitRendererBunit.cs index b9fb6a491..f28c37e2b 100644 --- a/tests/bunit.tests/Rendering/TestRendererTest.cs +++ b/tests/bunit.tests/Rendering/BunitRendererBunit.cs @@ -5,9 +5,9 @@ namespace Bunit.Rendering; -public partial class TestRendererTest : TestContext +public partial class BunitRendererBunit : TestContext { - public TestRendererTest(ITestOutputHelper outputHelper) + public BunitRendererBunit(ITestOutputHelper outputHelper) { TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(outputHelper); @@ -513,8 +513,26 @@ public void Test211() cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveWebAssembly}"); } + + [Fact(DisplayName = "given a IComponentActivator, " + + "when passed to constructor," + + "then it used to create components")] + public void Test1000() + { + var activatorMock = Substitute.For(); + activatorMock.CreateInstance(typeof(Wrapper)).Returns(new Wrapper()); + using var renderer = new BunitRenderer( + Services.GetService(), + Services, + NullLoggerFactory.Instance, + activatorMock); + + renderer.RenderComponent(new ComponentParameterCollection()); + + activatorMock.Received(1).CreateInstance(typeof(Wrapper)); + } - private TestRenderer CreateRenderer() => new TestRenderer( + private BunitRenderer CreateRenderer() => new BunitRenderer( Services.GetRequiredService(), Services, NullLoggerFactory.Instance); diff --git a/tests/bunit.tests/Rendering/TestRendererTest.net5.cs b/tests/bunit.tests/Rendering/TestRendererTest.net5.cs deleted file mode 100644 index 4e1fdb621..000000000 --- a/tests/bunit.tests/Rendering/TestRendererTest.net5.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Microsoft.Extensions.Logging.Abstractions; - -namespace Bunit.Rendering; - -public partial class TestRendererTest : TestContext -{ - [Fact(DisplayName = "given a IComponentActivator, " + - "when passed to constructor," + - "then it used to create components")] - public void Test1000() - { - var activatorMock = Substitute.For(); - activatorMock.CreateInstance(typeof(Wrapper)).Returns(new Wrapper()); - using var renderer = new TestRenderer( - Services.GetService(), - Services, - NullLoggerFactory.Instance, - activatorMock); - - renderer.RenderComponent(new ComponentParameterCollection()); - - activatorMock.Received(1).CreateInstance(typeof(Wrapper)); - } -} From 8e256ff208c57f4cc47d6659f8593a6188349352 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 16:57:00 +0100 Subject: [PATCH 013/100] refactor: All rendering methods are surfaced as "Render" --- MIGRATION.md | 3 + bunit.sln | 1 + .../mstest/HelloWorldExplicitContextTest.cs | 2 +- docs/samples/tests/mstest/HelloWorldTest.cs | 2 +- .../nunit/HelloWorldExplicitContextTest.cs | 2 +- .../nunit/HelloWorldInstancePerTestCase.cs | 2 +- docs/samples/tests/nunit/HelloWorldTest.cs | 2 +- .../tests/xunit/AllKindsOfParamsTest.cs | 74 +++++++------- docs/samples/tests/xunit/AsyncDataTest.cs | 6 +- .../tests/xunit/CascadingParams1Test.cs | 2 +- .../tests/xunit/CascadingParams2Test.cs | 2 +- .../tests/xunit/CascadingParams3Test.cs | 2 +- .../tests/xunit/ChildContentParams1Test.cs | 2 +- .../tests/xunit/ChildContentParams2Test.cs | 2 +- .../tests/xunit/ChildContentParams3Test.cs | 2 +- .../tests/xunit/ChildContentParams4Test.cs | 2 +- docs/samples/tests/xunit/ClickMeTest.cs | 2 +- .../xunit/ComponentFactoryExampleTest.cs | 2 +- docs/samples/tests/xunit/CounterTest.cs | 2 +- .../samples/tests/xunit/CounterTestWithCtx.cs | 2 +- .../xunit/CounterWithFancyParagraphTest.cs | 4 +- .../tests/xunit/DisposeComponentsTest.cs | 6 +- .../tests/xunit/EventCallbackParamsTest.cs | 2 +- .../xunit/HelloWorldExplicitContextTest.cs | 2 +- docs/samples/tests/xunit/HelloWorldTest.cs | 2 +- .../tests/xunit/InjectAuthServiceTest.cs | 4 +- .../tests/xunit/NestedComponentTest.cs | 2 +- .../tests/xunit/NonBlazorTypesParamsTest.cs | 2 +- docs/samples/tests/xunit/ReRenderTest.cs | 14 +-- .../tests/xunit/RenderFragmentParams1Test.cs | 2 +- .../tests/xunit/RenderFragmentParams2Test.cs | 2 +- .../tests/xunit/RenderFragmentParams3Test.cs | 2 +- .../tests/xunit/RenderFragmentParams4Test.cs | 2 +- docs/samples/tests/xunit/RenderTreeTest.cs | 4 +- docs/samples/tests/xunit/SemanticHtmlTest.cs | 2 +- .../tests/xunit/TemplateParams1Test.cs | 2 +- .../tests/xunit/TemplateParams2Test.cs | 2 +- docs/samples/tests/xunit/TwoWayBindingTest.cs | 2 +- .../tests/xunit/UnmatchedParamsTest.cs | 2 +- docs/samples/tests/xunit/UserInfoTest.cs | 8 +- docs/samples/tests/xunit/UserRightsTest.cs | 16 +-- .../tests/xunit/VerifyMarkupExamples.cs | 10 +- .../tests/xunit/WeatherForecastsTest.cs | 4 +- .../docs/getting-started/writing-tests.md | 6 +- .../interaction/trigger-event-handlers.md | 2 +- docs/site/docs/interaction/trigger-renders.md | 12 +-- .../passing-parameters-to-components.md | 8 +- .../docs/providing-input/root-render-tree.md | 2 +- .../docs/test-doubles/emulating-ijsruntime.md | 2 +- .../fake-webassemblyhostenvironment.md | 4 +- docs/site/docs/test-doubles/input-file.md | 2 +- .../docs/test-doubles/navigation-manager.md | 8 +- .../test-doubles/persistentcomponentstate.md | 4 +- .../verification/verify-component-state.md | 8 +- .../template/CounterCSharpTests.cs | 4 +- .../ComponentParameterCollectionBuilder.cs | 4 +- .../Extensions/BunitRendererExtensions.cs | 8 +- .../RenderedComponentRenderExtensions.cs | 18 ++-- src/bunit/Rendering/BunitRenderer.cs | 2 +- src/bunit/TestContext.cs | 6 +- src/bunit/TestContextWrapper.cs | 8 +- .../Web.Stub/AddStubGeneratorTests.cs | 4 +- .../CompareToDiffingExtensionsTest.cs | 16 +-- .../MarkupMatchesAssertExtensionsTest.cs | 10 +- .../MarkupMatchesAssertExtensionsTest.net5.cs | 2 +- .../BlazorE2E/ComponentRenderingTest.cs | 96 +++++++++--------- .../ConditionalComponentFactoryTest.cs | 6 +- .../GenericComponentFactoryTest.cs | 2 +- .../InstanceComponentFactoryTest.cs | 6 +- .../StubComponentFactoryTest.cs | 18 ++-- .../TypeBasedComponentFactoryTest.cs | 4 +- ...omponentParameterCollectionBuilderTests.cs | 4 +- ...onentParameterCollectionBuilderTests.razor | 2 +- ...ilsElementEventDispatcherExtensionsTest.cs | 2 +- .../EventDispatchExtensionsTest.cs | 4 +- .../GeneralEventDispatchExtensionsTest.cs | 42 ++++---- .../InputEventDispatchExtensionsTest.cs | 4 +- .../Extensions/InputFile/InputFileTests.cs | 10 +- .../RefreshableQueryCollectionTest.cs | 10 +- .../RefreshingWrappedElementTest.cs | 14 +-- .../RenderedComponentRenderExtensionsTest.cs | 6 +- ...tForElementsHelperExtensions.Async.Test.cs | 14 +-- ...mentWaitForElementsHelperExtensionsTest.cs | 14 +-- ...eredFragmentWaitForHelperExtensionsTest.cs | 16 +-- .../FocusAsyncInvocationHandlerTest.cs | 6 +- .../FocusOnNavigateHandlerTest.cs | 4 +- ...irtualizeJSRuntimeInvocationHandlerTest.cs | 12 +-- .../Rendering/BunitComponentActivatorTest.cs | 6 +- .../Rendering/BunitRendererBunit.cs | 97 +++++++------------ .../Rendering/Internal/HtmlizerTests.cs | 8 +- .../Rendering/RenderedComponentTest.cs | 26 ++--- .../Rendering/RenderedFragmentTest.cs | 28 +++--- .../Rendering/RootRenderTreeTest.cs | 20 ++-- tests/bunit.tests/TestContextTest.cs | 44 ++++----- .../Authorization/AuthorizationTest.cs | 38 ++++---- .../BunitSignOutSessionStateManagerTest.cs | 2 +- .../BunitWebAssemblyHostEnvironmentTest.cs | 4 +- .../Components/ComponentDoubleBaseTest.cs | 2 +- .../TestDoubles/Components/StubTest.cs | 4 +- .../BunitNavigationManagerTest.cs | 8 +- .../BunitPersistentComponentStateTest.cs | 4 +- tests/bunit.tests/TestServiceProviderTest.cs | 8 +- 102 files changed, 461 insertions(+), 488 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 29339e908..d9726ca1c 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -42,3 +42,6 @@ The `AddTestAuthorization` method on `TestContext` has been renamed to `AddAutho ## Merged `TestContext` and `TestContextBase` The `TestContext` and `TestContextBase` classes have been merged into a single `TestContext` class. All references to `TestContextBase` should replace them with `TestContext` to migrate. + +## Renamed all `RenderComponent` and `SetParametersAndRender` to `Render` +To make the API more consistent, `RenderComponent` and `SetParametersAndRender` methods have been renamed to `Render`. diff --git a/bunit.sln b/bunit.sln index 117ccb6ea..9a284fd0b 100644 --- a/bunit.sln +++ b/bunit.sln @@ -69,6 +69,7 @@ Global {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Release|Any CPU.Build.0 = Release|Any CPU + {1DA6EFDE-81A1-4324-A56C-40BEE14A75BA}.Debug|Any CPU.Build.0 = Debug|Any CPU {6127D121-9387-451B-B15D-8350A32D3001}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6127D121-9387-451B-B15D-8350A32D3001}.Release|Any CPU.ActiveCfg = Release|Any CPU {7972A80F-30DC-4EF4-9294-7D4DD2965882}.Debug|Any CPU.ActiveCfg = Debug|Any CPU diff --git a/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs b/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs index 32734e2fe..a4b7942af 100644 --- a/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs +++ b/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs @@ -13,7 +13,7 @@ public void HelloWorldComponentRendersCorrectly() using var ctx = new Bunit.TestContext(); // Act - var cut = ctx.RenderComponent(); + var cut = ctx.Render(); // Assert cut.MarkupMatches("

    Hello world from Blazor

    "); diff --git a/docs/samples/tests/mstest/HelloWorldTest.cs b/docs/samples/tests/mstest/HelloWorldTest.cs index 13c8f69c7..a83afd638 100644 --- a/docs/samples/tests/mstest/HelloWorldTest.cs +++ b/docs/samples/tests/mstest/HelloWorldTest.cs @@ -10,7 +10,7 @@ public class HelloWorldTest : BunitTestContext public void HelloWorldComponentRendersCorrectly() { // Act - var cut = RenderComponent(); + var cut = Render(); // Assert cut.MarkupMatches("

    Hello world from Blazor

    "); diff --git a/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs b/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs index a35a15f7d..6727db19d 100644 --- a/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs +++ b/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs @@ -12,7 +12,7 @@ public void HelloWorldComponentRendersCorrectly() using var ctx = new Bunit.TestContext(); // Act - var cut = ctx.RenderComponent(); + var cut = ctx.Render(); // Assert cut.MarkupMatches("

    Hello world from Blazor

    "); diff --git a/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs b/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs index 95f6edd23..b5d7142be 100644 --- a/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs +++ b/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs @@ -9,7 +9,7 @@ public class HelloWorldInstancePerTestCase : Bunit.TestContext public void HelloWorldComponentRendersCorrectly() { // Act - var cut = RenderComponent(); + var cut = Render(); // Assert cut.MarkupMatches("

    Hello world from Blazor

    "); diff --git a/docs/samples/tests/nunit/HelloWorldTest.cs b/docs/samples/tests/nunit/HelloWorldTest.cs index d8ad7011d..cce56a764 100644 --- a/docs/samples/tests/nunit/HelloWorldTest.cs +++ b/docs/samples/tests/nunit/HelloWorldTest.cs @@ -9,7 +9,7 @@ public class HelloWorldTest : BunitTestContext public void HelloWorldComponentRendersCorrectly() { // Act - var cut = RenderComponent(); + var cut = Render(); // Assert cut.MarkupMatches("

    Hello world from Blazor

    "); diff --git a/docs/samples/tests/xunit/AllKindsOfParamsTest.cs b/docs/samples/tests/xunit/AllKindsOfParamsTest.cs index 13179ddc5..18c4fec4d 100644 --- a/docs/samples/tests/xunit/AllKindsOfParamsTest.cs +++ b/docs/samples/tests/xunit/AllKindsOfParamsTest.cs @@ -14,25 +14,25 @@ public class AllKindsOfParamsTest : TestContext public void NonBlazorParamTypes() { // Using C# tuple with hardcoded name - var cut1 = RenderComponent( + var cut1 = Render( ("Numbers", 42), ("Lines", new List { "Hello", "World" }) ); // Using C# tuple with refactor safe name - var cut2 = RenderComponent( + var cut2 = Render( (nameof(NonBlazorTypesParams.Numbers), 42), (nameof(NonBlazorTypesParams.Lines), new List { "Hello", "World" }) ); // Using factory method - var cut3 = RenderComponent( + var cut3 = Render( Parameter("Numbers", 42), Parameter("Lines", new List { "Hello", "World" }) ); // Using parameter builder - var cut4 = RenderComponent(parameters => parameters + var cut4 = Render(parameters => parameters .Add(p => p.Numbers, 42) .Add(p => p.Lines, new List { "Hello", "World" }) ); @@ -43,7 +43,7 @@ public void EventCallbackTypes() { // Using factory method with hardcoded name - var cut1 = RenderComponent( + var cut1 = Render( EventCallback("OnClick", (MouseEventArgs args) => { /* handle callback */ @@ -55,7 +55,7 @@ public void EventCallbackTypes() ); // Using factory method refactor safe name - var cut2 = RenderComponent( + var cut2 = Render( EventCallback(nameof(EventCallbackParams.OnClick), (MouseEventArgs args) => { /* handle callback */ @@ -67,7 +67,7 @@ public void EventCallbackTypes() ); // Using parameter builder - var cut3 = RenderComponent(parameters => parameters + var cut3 = Render(parameters => parameters .Add(p => p.OnClick, args => { /* handle callback */ @@ -83,12 +83,12 @@ public void EventCallbackTypes() public void HtmlAsChildContent() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( ChildContent("

    Hello World

    ") ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddChildContent("

    Hello World

    ") ); } @@ -97,12 +97,12 @@ public void HtmlAsChildContent() public void ComponentAsChildContent() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( ChildContent() ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddChildContent() ); } @@ -111,7 +111,7 @@ public void ComponentAsChildContent() public void ComponentWithParamsAsChildContent() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( ChildContent( ("Heading", "Alert heading"), ("Type", AlertType.Warning), @@ -120,7 +120,7 @@ public void ComponentWithParamsAsChildContent() ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddChildContent(alertParameters => alertParameters .Add(p => p.Heading, "Alert heading") .Add(p => p.Type, AlertType.Warning) @@ -133,7 +133,7 @@ public void ComponentWithParamsAsChildContent() public void ComponentAndMarkupAsChildContent() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( ChildContent("

    Below you will find a most interesting alert!

    "), ChildContent( ("Heading", "Alert heading"), @@ -143,7 +143,7 @@ public void ComponentAndMarkupAsChildContent() ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddChildContent("

    Below you will find a most interesting alert!

    ") .AddChildContent(childParams => childParams .Add(p => p.Heading, "Alert heading") @@ -157,12 +157,12 @@ public void ComponentAndMarkupAsChildContent() public void HtmlAsRenderFragment() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( RenderFragment("Content", "

    Hello World

    ") ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .Add(p => p.Content, "

    Hello World

    ") ); } @@ -171,12 +171,12 @@ public void HtmlAsRenderFragment() public void ComponentAsRenderFragment() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( RenderFragment("Content") ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .Add(p => p.Content) ); } @@ -185,7 +185,7 @@ public void ComponentAsRenderFragment() public void ComponentWithParamsAsRenderFragment() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( RenderFragment("Content", ("Heading", "Alert heading"), ("Type", AlertType.Warning), @@ -194,7 +194,7 @@ public void ComponentWithParamsAsRenderFragment() ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .Add(p => p.Content, alertParameters => alertParameters .Add(p => p.Heading, "Alert heading") .Add(p => p.Type, AlertType.Warning) @@ -207,7 +207,7 @@ public void ComponentWithParamsAsRenderFragment() public void ComponentAndMarkupAsRenderFragment() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( RenderFragment("Content", "

    Below you will find a most interesting alert!

    "), RenderFragment("Content", ("Heading", "Alert heading"), @@ -217,7 +217,7 @@ public void ComponentAndMarkupAsRenderFragment() ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .Add(p => p.Content, "

    Below you will find a most interesting alert!

    ") .Add(p => p.Content, childParams => childParams .Add(p => p.Heading, "Alert heading") @@ -231,13 +231,13 @@ public void ComponentAndMarkupAsRenderFragment() public void HtmlTemplateParams() { // Using factory method - var cut1 = RenderComponent>( + var cut1 = Render>( ("Items", new string[] { "Foo", "Bar", "Baz" }), Template("Template", item => $"{item}") ); // Using parameter builder - var cut2 = RenderComponent>(parameters => parameters + var cut2 = Render>(parameters => parameters .Add(p => p.Items, new[] { "Foo", "Bar", "Baz" }) .Add(p => p.Template, item => $"{item}") ); @@ -247,7 +247,7 @@ public void HtmlTemplateParams() public void HtmlAndComponentTemplateParams() { // Using factory method - var cut1 = RenderComponent>( + var cut1 = Render>( ("Items", new string[] { "Foo", "Bar", "Baz" }), Template("Template", value => new ComponentParameter[] { @@ -256,7 +256,7 @@ public void HtmlAndComponentTemplateParams() ); // Using parameter builder - var cut2 = RenderComponent>(parameters => parameters + var cut2 = Render>(parameters => parameters .Add(p => p.Items, new[] { "Foo", "Bar", "Baz" }) .Add(p => p.Template, value => itemParams => itemParams .Add(p => p.Value, value) @@ -268,12 +268,12 @@ public void HtmlAndComponentTemplateParams() public void UnmatchedParamsTest() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( ("some-unknown-param", "a value") ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddUnmatched("some-unknown-param", "a value") ); } @@ -284,17 +284,17 @@ public void UnnamedCascadingParamsTest() var isDarkTheme = true; // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( CascadingValue(isDarkTheme) ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddCascadingValue(isDarkTheme) ); // Using parameter builder and selecting unnamed cascading parameter - var cut3 = RenderComponent(parameters => parameters + var cut3 = Render(parameters => parameters .Add(p => p.IsDarkTheme, isDarkTheme) ); } @@ -303,12 +303,12 @@ public void UnnamedCascadingParamsTest() public void NamedCascadingParamsTest() { // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( CascadingValue("LoggedInUser", "Egil Hansen") ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .Add(p => p.UserName, "Egil Hansen") ); } @@ -319,21 +319,21 @@ public void UnnamedAndNamedCascadingParamsTest() var isDarkTheme = true; // Using factory method - var cut1 = RenderComponent( + var cut1 = Render( CascadingValue(isDarkTheme), CascadingValue("LoggedInUser", "Egil Hansen"), CascadingValue("LoggedInEmail", "egil@example.com") ); // Using parameter builder - var cut2 = RenderComponent(parameters => parameters + var cut2 = Render(parameters => parameters .AddCascadingValue(isDarkTheme) .Add(p => p.UserName, "Egil Hansen") .Add(p => p.Email, "egil@example.com") ); // Using parameter builder and selecting unnamed cascading parameter - var cut3 = RenderComponent(parameters => parameters + var cut3 = Render(parameters => parameters .Add(p => p.IsDarkTheme, isDarkTheme) .Add(p => p.UserName, "Egil Hansen") .Add(p => p.Email, "egil@example.com") diff --git a/docs/samples/tests/xunit/AsyncDataTest.cs b/docs/samples/tests/xunit/AsyncDataTest.cs index edb90e0cc..9731faf40 100644 --- a/docs/samples/tests/xunit/AsyncDataTest.cs +++ b/docs/samples/tests/xunit/AsyncDataTest.cs @@ -13,7 +13,7 @@ public void LoadDataAsync() { // Arrange var textService = new TaskCompletionSource(); - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .Add(p => p.TextService, textService.Task) ); @@ -32,7 +32,7 @@ public void LoadDataAsyncWithTimeout() { // Arrange var textService = new TaskCompletionSource(); - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .Add(p => p.TextService, textService.Task) ); @@ -51,7 +51,7 @@ public void LoadDataAsyncAssertion() { // Arrange var textService = new TaskCompletionSource(); - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .Add(p => p.TextService, textService.Task) ); diff --git a/docs/samples/tests/xunit/CascadingParams1Test.cs b/docs/samples/tests/xunit/CascadingParams1Test.cs index a6816f45c..9bb71cd97 100644 --- a/docs/samples/tests/xunit/CascadingParams1Test.cs +++ b/docs/samples/tests/xunit/CascadingParams1Test.cs @@ -15,7 +15,7 @@ public void Test() { var isDarkTheme = true; - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .Add(p => p.IsDarkTheme, isDarkTheme) ); } diff --git a/docs/samples/tests/xunit/CascadingParams2Test.cs b/docs/samples/tests/xunit/CascadingParams2Test.cs index 2d72965e8..193e593fa 100644 --- a/docs/samples/tests/xunit/CascadingParams2Test.cs +++ b/docs/samples/tests/xunit/CascadingParams2Test.cs @@ -13,7 +13,7 @@ public class CascadingParams2Test : TestContext [Fact] public void Test() { - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .Add(p => p.UserName, "Name of User") ); } diff --git a/docs/samples/tests/xunit/CascadingParams3Test.cs b/docs/samples/tests/xunit/CascadingParams3Test.cs index 23e736fff..0a6e49d26 100644 --- a/docs/samples/tests/xunit/CascadingParams3Test.cs +++ b/docs/samples/tests/xunit/CascadingParams3Test.cs @@ -15,7 +15,7 @@ public void Test() { var isDarkTheme = true; - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .Add(p => p.IsDarkTheme, isDarkTheme) .Add(p => p.UserName, "Name of User") .Add(p => p.Email, "user@example.com") diff --git a/docs/samples/tests/xunit/ChildContentParams1Test.cs b/docs/samples/tests/xunit/ChildContentParams1Test.cs index 87299ec7b..b480642da 100644 --- a/docs/samples/tests/xunit/ChildContentParams1Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams1Test.cs @@ -13,7 +13,7 @@ public class ChildContentParams1Test : TestContext [Fact] public void Test() { - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent("

    Hello World

    ") ); } diff --git a/docs/samples/tests/xunit/ChildContentParams2Test.cs b/docs/samples/tests/xunit/ChildContentParams2Test.cs index cc2e57c74..8c0c2b4f9 100644 --- a/docs/samples/tests/xunit/ChildContentParams2Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams2Test.cs @@ -13,7 +13,7 @@ public class ChildContentParams2Test : TestContext [Fact] public void Test() { - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent() ); } diff --git a/docs/samples/tests/xunit/ChildContentParams3Test.cs b/docs/samples/tests/xunit/ChildContentParams3Test.cs index 58aaa4d98..880c4442a 100644 --- a/docs/samples/tests/xunit/ChildContentParams3Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams3Test.cs @@ -13,7 +13,7 @@ public class ChildContentParams3Test : TestContext [Fact] public void Test() { - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent(alertParameters => alertParameters .Add(p => p.Heading, "Alert heading") .Add(p => p.Type, AlertType.Warning) diff --git a/docs/samples/tests/xunit/ChildContentParams4Test.cs b/docs/samples/tests/xunit/ChildContentParams4Test.cs index cbbf4e0b6..54388d9e5 100644 --- a/docs/samples/tests/xunit/ChildContentParams4Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams4Test.cs @@ -13,7 +13,7 @@ public class ChildContentParams4Test : TestContext [Fact] public void Test() { - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent("

    Below you will find a most interesting alert!

    ") .AddChildContent(childParams => childParams .Add(p => p.Heading, "Alert heading") diff --git a/docs/samples/tests/xunit/ClickMeTest.cs b/docs/samples/tests/xunit/ClickMeTest.cs index 4e6a2186e..6c14410a6 100644 --- a/docs/samples/tests/xunit/ClickMeTest.cs +++ b/docs/samples/tests/xunit/ClickMeTest.cs @@ -10,7 +10,7 @@ public class ClickMeTest : TestContext public void Test() { // Arrange - var cut = RenderComponent(); + var cut = Render(); var buttonElement = cut.Find("button"); // Act diff --git a/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs b/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs index f11a8c898..47893e27b 100644 --- a/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs +++ b/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs @@ -13,7 +13,7 @@ public void ReplacesFooWithBarDuringTest() ComponentFactories.Add(new FooBarComponentFactory()); // Act - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent()); // Assert that there are no in render tree, diff --git a/docs/samples/tests/xunit/CounterTest.cs b/docs/samples/tests/xunit/CounterTest.cs index 366a3f5f4..7f44ad736 100644 --- a/docs/samples/tests/xunit/CounterTest.cs +++ b/docs/samples/tests/xunit/CounterTest.cs @@ -9,7 +9,7 @@ public class CounterTest : TestContext public void CounterShouldIncrementWhenClicked() { // Arrange: render the Counter.razor component - var cut = RenderComponent(); + var cut = Render(); // Act: find and click the
    "; - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches(expectedMarkup); } diff --git a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs index d455b112d..969805618 100644 --- a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs +++ b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs @@ -5,7 +5,7 @@ public partial class MarkupMatchesAssertExtensionsTest : TestContext [Fact(DisplayName = "MarkupMatches correctly ignores scoped CSS attributes")] public void Test_net5_001() { - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches("

    Hello Pink World!

    "); } diff --git a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs index 212e01284..039ddac08 100644 --- a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs +++ b/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs @@ -24,29 +24,29 @@ public ComponentRenderingTest(ITestOutputHelper outputHelper) Services.AddXunitLogger(outputHelper); JSInterop.Mode = JSRuntimeMode.Loose; } - + [Fact] public void CanRenderTextOnlyComponent() { - var cut = RenderComponent(); + var cut = Render(); Assert.Equal("Hello from TextOnlyComponent", cut.Markup); } // This verifies that we've correctly configured the Razor language version via MSBuild. // See #974 [Fact] - public void CanRenderComponentWithDataDash() + public void CanRenderWithDataDash() { - var cut = RenderComponent(); + var cut = Render(); var element = cut.Find("#cool_beans"); Assert.Equal("17", element.GetAttribute("data-tab")); Assert.Equal("17", element.TextContent); } [Fact] - public void CanRenderComponentWithAttributes() + public void CanRenderWithAttributes() { - var cut = RenderComponent(); + var cut = Render(); var styledElement = cut.Find("h1"); Assert.Equal("Hello, world!", styledElement.TextContent); Assert.Equal("color: red;", styledElement.GetAttribute("style")); @@ -57,7 +57,7 @@ public void CanRenderComponentWithAttributes() public void CanTriggerEvents() { // Initial count is zero - var cut = RenderComponent(); + var cut = Render(); var countDisplayElement = cut.Find("p"); Assert.Equal("Current count: 0", countDisplayElement.TextContent); @@ -71,7 +71,7 @@ public void CanTriggerEvents() public async Task CanTriggerAsyncEventHandlers() { // Initial state is stopped - var cut = RenderComponent(); + var cut = Render(); var stateElement = cut.Find("#state"); Assert.Equal("Stopped", stateElement.TextContent); @@ -88,7 +88,7 @@ public async Task CanTriggerAsyncEventHandlers() public void CanTriggerAsyncEventHandlers_Sync() { // Initial state is stopped - var cut = RenderComponent(); + var cut = Render(); var stateElement = cut.Find("#state"); Assert.Equal("Stopped", stateElement.TextContent); @@ -104,7 +104,7 @@ public void CanTriggerAsyncEventHandlers_Sync() public void CanTriggerKeyPressEvents() { // List is initially empty - var cut = RenderComponent(); + var cut = Render(); var inputElement = cut.Find("input"); var liElements = cut.FindAll("li", enableAutoRefresh: true); liElements.ShouldBeEmpty(); @@ -123,7 +123,7 @@ public void CanTriggerKeyPressEvents() [Fact] public void CanAddAndRemoveEventHandlersDynamically() { - var cut = RenderComponent(); + var cut = Render(); var countDisplayElement = cut.Find("p"); var incrementButton = cut.Find("button"); var toggleClickHandlerCheckbox = cut.Find("[type=checkbox]"); @@ -149,7 +149,7 @@ public void CanAddAndRemoveEventHandlersDynamically() [Fact] public void CanRenderChildComponents() { - var cut = RenderComponent(); + var cut = Render(); Assert.Equal("Parent component", cut.Find("fieldset > legend").TextContent); var styledElement = cut.Find("fieldset > h1"); @@ -161,14 +161,14 @@ public void CanRenderChildComponents() [Fact(DisplayName = "Verifies we can render HTML content as a single block")] public void CanRenderChildContent_StaticHtmlBlock() { - var cut = RenderComponent(); + var cut = Render(); Assert.Equal("

    Some-Static-Text

    ", cut.Find("#foo").InnerHtml); } [Fact(DisplayName = "Verifies we can rewrite more complex HTML content into blocks")] public void CanRenderChildContent_MixedHtmlBlock() { - var cut = RenderComponent(); + var cut = Render(); var one = cut.Find("#one"); Assert.Equal("

    Some-Static-Text

    ", one.InnerHtml); @@ -186,7 +186,7 @@ public void CanRenderChildContent_MixedHtmlBlock() [Fact(DisplayName = "Verifies we can rewrite HTML blocks with encoded HTML")] public void CanRenderChildContent_EncodedHtmlInBlock() { - var cut = RenderComponent(); + var cut = Render(); var one = cut.Find("#one"); Assert.Equal("

    Some-Static-Text

    ", one.InnerHtml); @@ -205,7 +205,7 @@ public void CanRenderChildContent_EncodedHtmlInBlock() public void CanTriggerEventsOnChildComponents() { // Counter is displayed as child component. Initial count is zero. - var cut = RenderComponent(); + var cut = Render(); // Clicking increments count in child component cut.Find("button").Click(); @@ -217,7 +217,7 @@ public void CanTriggerEventsOnChildComponents() public void ChildComponentsRerenderWhenPropertiesChanged() { // Count value is displayed in child component with initial value zero - var cut = RenderComponent(); + var cut = Render(); var wholeCounterElement = cut.Find("p"); var messageElementInChild = cut.Find("p .message"); Assert.Equal("Current count: 0", wholeCounterElement.TextContent); @@ -232,7 +232,7 @@ public void ChildComponentsRerenderWhenPropertiesChanged() public void CanAddAndRemoveChildComponentsDynamically() { // Initially there are zero child components - var cut = RenderComponent(); + var cut = Render(); var addButton = cut.Find(".addChild"); var removeButton = cut.Find(".removeChild"); Assert.Empty(cut.FindAll("p")); @@ -265,7 +265,7 @@ public void CanAddAndRemoveChildComponentsDynamically() public void ChildComponentsNotifiedWhenPropertiesChanged() { // Child component receives notification that lets it compute a property before first render - var cut = RenderComponent(); + var cut = Render(); var suppliedValueElement = cut.Find(".supplied"); var computedValueElement = cut.Find(".computed"); var incrementButton = cut.Find("button"); @@ -282,7 +282,7 @@ public void ChildComponentsNotifiedWhenPropertiesChanged() public void CanRenderFragmentsWhilePreservingSurroundingElements() { // Initially, the region isn't shown - var cut = RenderComponent(); + var cut = Render(); var originalButton = cut.Find("button"); var fragmentElements = cut.FindAll("p[name=fragment-element]", enableAutoRefresh: true); @@ -306,7 +306,7 @@ public void CanUseViewImportsHierarchically() { // The component is able to compile and output these type names only because // of the _ViewImports.cshtml files at the same and ancestor levels - var cut = RenderComponent(); + var cut = Render(); Assert.Collection( cut.FindAll("p"), elem => Assert.Equal(typeof(Complex).FullName, elem.TextContent), @@ -316,7 +316,7 @@ public void CanUseViewImportsHierarchically() [Fact] public void CanRenderSvgWithCorrectNamespace() { - var cut = RenderComponent(); + var cut = Render(); var svgElement = cut.Find("svg"); Assert.NotNull(svgElement); @@ -332,7 +332,7 @@ public void CanRenderSvgWithCorrectNamespace() [Fact] public void CanRenderSvgChildComponentWithCorrectNamespace() { - var cut = RenderComponent(); + var cut = Render(); var svgElement = cut.Find("svg"); Assert.NotNull(svgElement); @@ -344,7 +344,7 @@ public void CanRenderSvgChildComponentWithCorrectNamespace() [Fact] public void LogicalElementInsertionWorksHierarchically() { - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches("First Second Third"); } @@ -353,7 +353,7 @@ public void CanUseJSInteropToReferenceElements() { // NOTE: This test required JS to modify the DOM. Test rewritten to use MockJSRuntime // The original test code is here: - // var cut = RenderComponent(); + // var cut = Render(); // var inputElement = cut.Find("#capturedElement"); // var buttonElement = cut.Find("button"); @@ -364,7 +364,7 @@ public void CanUseJSInteropToReferenceElements() // buttonElement.Click(); // Assert.Equal("Clicks: 2", inputElement.GetAttribute("value")); - var cut = RenderComponent(); + var cut = Render(); var inputElement = cut.Find("#capturedElement"); var refId = inputElement.GetAttribute(Htmlizer.ElementReferenceAttrName); var buttonElement = cut.Find("button"); @@ -381,7 +381,7 @@ public void CanCaptureReferencesToDynamicallyAddedElements() { // NOTE: This test required JS to modify the DOM. Test rewritten to use MockJSRuntime // The original test code is here: - // var cut = RenderComponent(); + // var cut = Render(); // var buttonElement = cut.Find("button"); // var checkbox = cut.Find("input[type=checkbox]"); // @@ -402,7 +402,7 @@ public void CanCaptureReferencesToDynamicallyAddedElements() // buttonElement.Click(); // Assert.Equal("Clicks: 1", () => inputElement.GetAttribute("value")); - var cut = RenderComponent(); + var cut = Render(); var buttonElement = cut.Find("button"); var checkbox = cut.Find("input[type=checkbox]"); @@ -431,7 +431,7 @@ public void CanCaptureReferencesToDynamicallyAddedElements() [Fact] public void CanCaptureReferencesToDynamicallyAddedComponents() { - var cut = RenderComponent(); + var cut = Render(); var incrementButton = cut.Find("#child-component button"); var resetButton = cut.Find("#reset-child"); var toggleChildCheckbox = cut.Find("#toggle-child"); @@ -462,14 +462,14 @@ public void CanCaptureReferencesToDynamicallyAddedComponents() // [Fact] // public void CanUseJSInteropForRefElementsDuringOnAfterRender() // { - // var cut = RenderComponent(); + // var cut = Render(); // Assert.Equal("Value set after render", () => Browser.Find("input").GetAttribute("value")); // } [Fact] public void CanRenderMarkupBlocks() { - var cut = RenderComponent(); + var cut = Render(); // Static markup Assert.Equal("attributes", cut.Find("p span#attribute-example").TextContent); @@ -491,7 +491,7 @@ public void CanRenderMarkupBlocks() [Fact] public void CanRenderRazorTemplates() { - var cut = RenderComponent(); + var cut = Render(); // code block template (component parameter) var element = cut.Find("div#codeblocktemplate ol"); @@ -505,7 +505,7 @@ public void CanRenderRazorTemplates() [Fact] public void CanRenderMultipleChildContent() { - var cut = RenderComponent(); + var cut = Render(); var table = cut.Find("table"); @@ -536,7 +536,7 @@ public async Task CanAcceptSimultaneousRenderRequests() string.Empty, Enumerable.Range(0, 100).Select(_ => "😊")); - var cut = RenderComponent(); + var cut = Render(); // It's supposed to pause the rendering for this long. The WaitAssert below // allows it to take up extra time if needed. @@ -557,7 +557,7 @@ public void CanAcceptSimultaneousRenderRequests_Sync() string.Empty, Enumerable.Range(0, 100).Select(_ => "😊")); - var cut = RenderComponent(); + var cut = Render(); // It's supposed to pause the rendering for this long. The WaitAssert below // allows it to take up extra time if needed. @@ -574,7 +574,7 @@ public void CanAcceptSimultaneousRenderRequests_Sync() [Trait("Category", "async")] public async Task CanDispatchRenderToSyncContext() { - var cut = RenderComponent(); + var cut = Render(); var result = cut.Find("#result"); cut.Find("#run-with-dispatch").Click(); @@ -586,7 +586,7 @@ public async Task CanDispatchRenderToSyncContext() [Trait("Category", "sync")] public void CanDispatchRenderToSyncContext_Sync() { - var cut = RenderComponent(); + var cut = Render(); var result = cut.Find("#result"); cut.Find("#run-with-dispatch").Click(); @@ -598,7 +598,7 @@ public void CanDispatchRenderToSyncContext_Sync() [Trait("Category", "async")] public async Task CanDoubleDispatchRenderToSyncContext() { - var cut = RenderComponent(); + var cut = Render(); var result = cut.Find("#result"); cut.Find("#run-with-double-dispatch").Click(); @@ -610,7 +610,7 @@ public async Task CanDoubleDispatchRenderToSyncContext() [Trait("Category", "sync")] public void CanDoubleDispatchRenderToSyncContext_Sync() { - var cut = RenderComponent(); + var cut = Render(); var result = cut.Find("#result"); cut.Find("#run-with-double-dispatch").Click(); @@ -621,7 +621,7 @@ public void CanDoubleDispatchRenderToSyncContext_Sync() [Fact] public void CanUseAddMultipleAttributes() { - var cut = RenderComponent(); + var cut = Render(); var element = cut.Find("#duplicate-on-element > div"); Assert.True(element.HasAttribute("bool")); // attribute is present @@ -637,7 +637,7 @@ public void CanUseAddMultipleAttributes() [Fact] public void CanPatchRenderTreeToMatchLatestDOMState() { - var cut = RenderComponent(); + var cut = Render(); var incompleteItemsSelector = ".incomplete-items li"; var completeItemsSelector = ".complete-items li"; @@ -660,7 +660,7 @@ public void CanPatchRenderTreeToMatchLatestDOMState() [Trait("Category", "async")] public async Task CanHandleRemovedParentObjects() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -672,7 +672,7 @@ public async Task CanHandleRemovedParentObjects() [Trait("Category", "sync")] public void CanHandleRemovedParentObjects_Sync() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -684,7 +684,7 @@ public void CanHandleRemovedParentObjects_Sync() [Trait("Category", "async")] public async Task CanHandleRemovedParentObjectsAsync() { - var cut = RenderComponent(); + var cut = Render(); await cut.Find("button").ClickAsync(new MouseEventArgs()); @@ -698,7 +698,7 @@ public async Task CanHandleRemovedParentObjectsAsync() [InlineData("<\"*?_'", "

    <\"*?_'

    ")] public void SomeEscapableCharactersDontGetEncoded(string input, string expected) { - var cut = RenderComponent( + var cut = Render( p => p.Add(s => s.Escaped, input)); cut.Markup.ShouldBe(expected); @@ -708,19 +708,19 @@ public void SomeEscapableCharactersDontGetEncoded(string input, string expected) [Trait("Category", "sync")] public async Task CanHandleRemovedParentObjectsAsync_Sync() { - var cut = RenderComponent(); + var cut = Render(); await cut.Find("button").ClickAsync(new MouseEventArgs()); cut.WaitForState(() => !cut.FindAll("div").Any()); cut.FindAll("div").Count.ShouldBe(0); } - + [Fact] public void CanHandleAndPassThroughPropertiesOfWrappedElements() { // Act - var component = RenderComponent(p => + var component = Render(p => { p.Add(c => c.IsDisabled, true); }); diff --git a/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs index 95ecf78e8..6a413bf19 100644 --- a/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs @@ -23,7 +23,7 @@ public void Test010() var mockComponent = Substitute.For(); ComponentFactories.Add(type => type == typeof(Simple1), _ => mockComponent); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.FindComponent() .Instance.ShouldBeSameAs(mockComponent); @@ -40,7 +40,7 @@ public void Test011() ); // Act - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.First) .Add(p => p.Second)); @@ -54,7 +54,7 @@ public void Test012() { ComponentFactories.Add(_ => false, _ => throw new NotImplementedException("DONT CALL FACTORY")); - Should.NotThrow(() => RenderComponent(ps => ps.AddChildContent())); + Should.NotThrow(() => Render(ps => ps.AddChildContent())); } private static IComponent CreateComponent(Type type, Simple1 simple1, NoArgs noArgs) diff --git a/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs index cba72719f..20bc753cd 100644 --- a/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs @@ -11,7 +11,7 @@ public void Test002() { ComponentFactories.Add(); - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches(@"
    Has ref = True
    "); } diff --git a/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs index 1beee0b90..ad3b35105 100644 --- a/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs @@ -16,7 +16,7 @@ public void Test010() var simple1Mock = Substitute.For(); ComponentFactories.Add(simple1Mock); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.FindComponent() .Instance.ShouldBeSameAs(simple1Mock); @@ -28,7 +28,7 @@ public void Test020() var simple1Mock = Substitute.For(); ComponentFactories.Add(simple1Mock); - Should.Throw(() => RenderComponent(ps => ps + Should.Throw(() => Render(ps => ps .Add(p => p.First) .Add(p => p.Second))); } @@ -39,7 +39,7 @@ public void Test021() var simple1Mock = Substitute.For(); ComponentFactories.Add(simple1Mock); - Should.Throw(() => RenderComponent(ps => ps + Should.Throw(() => Render(ps => ps .Add(p => p.First) .Add(p => p.Second))); } diff --git a/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs index 72801de80..9fdc34f94 100644 --- a/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs @@ -13,7 +13,7 @@ public void Test001() { ComponentFactories.AddStub(); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); } @@ -23,7 +23,7 @@ public void Test002() { ComponentFactories.AddStub(); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); } @@ -34,7 +34,7 @@ public void Test010(string randomText) { ComponentFactories.AddStub($"

    {randomText}

    "); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); cut.MarkupMatches($"

    {randomText}

    "); @@ -46,7 +46,7 @@ public void Test011(string randomText) { ComponentFactories.AddStub(b => b.AddMarkupContent(0, $"

    {randomText}

    ")); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); cut.MarkupMatches($"

    {randomText}

    "); @@ -58,7 +58,7 @@ public void Test0042(string regularParamValue) { ComponentFactories.AddStub>(ps => $"
    {ps.Get(x => x.RegularParam)}
    "); - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent>(ps => ps.Add(p => p.RegularParam, regularParamValue))); cut.MarkupMatches($"
    {regularParamValue}
    "); @@ -72,7 +72,7 @@ public void Test004(string regularParamValue) => builder => builder.AddMarkupContent(0, $"
    {ps.Get(x => x.RegularParam)}
    ")); - var cut = RenderComponent(parameters => parameters + var cut = Render(parameters => parameters .AddChildContent>(ps => ps.Add(p => p.RegularParam, regularParamValue))); cut.MarkupMatches($"
    {regularParamValue}
    "); @@ -83,7 +83,7 @@ public void Test003() { ComponentFactories.AddStub(componentType => componentType == typeof(CompA)); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); } @@ -94,7 +94,7 @@ public void Test023(string randomText) { ComponentFactories.AddStub(componentType => componentType == typeof(CompA), $"

    {randomText}

    "); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); cut.MarkupMatches($"

    {randomText}

    "); @@ -106,7 +106,7 @@ public void Test024(string randomText) { ComponentFactories.AddStub(componentType => componentType == typeof(CompA), b => b.AddMarkupContent(1, $"

    {randomText}

    ")); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.HasComponent>().ShouldBeTrue(); cut.MarkupMatches($"

    {randomText}

    "); diff --git a/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs index 1f391718c..34e114ec6 100644 --- a/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs @@ -17,7 +17,7 @@ public void Test010() var simple1Mock = Substitute.For(); ComponentFactories.Add(() => simple1Mock); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); cut.FindComponent() .Instance.ShouldBeSameAs(simple1Mock); @@ -28,7 +28,7 @@ public void Test011() { ComponentFactories.Add(() => Substitute.For()); - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.First) .Add(p => p.Second)); diff --git a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs index bc8f6409f..82645f1b1 100644 --- a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs +++ b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs @@ -703,7 +703,7 @@ public void Test315() var uri = navigationManager.GetUriWithQueryParameter("Query", "Test"); navigationManager.NavigateTo(uri); - var cut = RenderComponent(); + var cut = Render(); cut.Instance.Query.ShouldBe("Test"); } @@ -711,7 +711,7 @@ public void Test315() [Fact(DisplayName = "Throws an exception if a SupplyFromQueryParameter is passed as parameter")] public void Test316() { - Action action = () => RenderComponent( + Action action = () => Render( ps => ps.Add(p => p.Query, "Foo")); action.ShouldThrow() diff --git a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor index d72ee240d..69285be44 100644 --- a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor +++ b/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor @@ -7,7 +7,7 @@ var initialValue = "Hello"; // act - var bindMethod = RenderComponent(ps => ps + var bindMethod = Render(ps => ps .Bind( p => p.Foo, initialValue, diff --git a/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs index eb1ad67d7..fcd3173c3 100644 --- a/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs @@ -5,7 +5,7 @@ public class DetailsElementEventDispatcherExtensionsTest : TestContext [Fact(DisplayName = "Toggle raises ontoggle events")] public void Test200() { - var cut = RenderComponent(); + var cut = Render(); cut.FindAll("div > p").Count.ShouldBe(0); cut.Find("details").Toggle(); diff --git a/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs index 005fa7037..ec5688a44 100644 --- a/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs @@ -15,11 +15,11 @@ protected EventDispatchExtensionsTest(ITestOutputHelper outputHelper) } protected TriggerEventSpy CreateTriggerSpy(string element, string eventName) - => new(p => RenderComponent>(p), element, eventName); + => new(p => Render>(p), element, eventName); // This is a separate overload for useful in non-reflection based testing protected TriggerEventSpy CreateTriggerSpy(string element, string eventName) where T : EventArgs, new() - => new(p => RenderComponent>(p), element, eventName); + => new(p => Render>(p), element, eventName); protected void VerifyEventRaisesCorrectly(MethodInfo helper, TEventArgs expected, params (string MethodName, string EventName)[] methodNameEventMap) { diff --git a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs index b7461f78d..fe8b3b3f7 100644 --- a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs @@ -39,7 +39,7 @@ public void Test001() [Fact(DisplayName = "TriggerEventAsync throws if element does not contain an attribute with the blazor event-name")] public void Test002() { - var cut = RenderComponent(); + var cut = Render(); Should.Throw(() => cut.Find("h1").Click()); } @@ -62,7 +62,7 @@ public void Test003() "event handlers higher up the DOM tree is also triggered")] public void Test100() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("span").Click(); @@ -74,7 +74,7 @@ public void Test100() "event handlers higher up the DOM tree is triggered")] public void Test101() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -106,7 +106,7 @@ public void Test101() [InlineData("onselectionchange")] public async Task Test110(string eventName) { - var cut = RenderComponent(ps => ps.Add(p => p.EventName, eventName)); + var cut = Render(ps => ps.Add(p => p.EventName, eventName)); await cut.Find("#child").TriggerEventAsync(eventName, EventArgs.Empty); @@ -118,7 +118,7 @@ public async Task Test110(string eventName) [Fact(DisplayName = "When event has StopPropergation modifier, events does not bubble from target")] public async Task Test111() { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.EventName, "onclick") .Add(p => p.ChildStopPropagation, true)); @@ -132,7 +132,7 @@ public async Task Test111() [Fact(DisplayName = "When event has StopPropergation modifier, events does not bubble from parent of target")] public async Task Test112() { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.EventName, "onclick") .Add(p => p.ParentStopPropagation, true)); @@ -148,7 +148,7 @@ public async Task Test113( [CombinatorialValues("onclick", "ondblclick", "onmousedown", "onmousemove", "onmouseup")] string eventName, [CombinatorialValues("button", "input", "textarea", "select")] string elementType) { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.EventName, eventName) .Add(p => p.ChildElementType, elementType) .Add(p => p.ChildElementDisabled, true)); @@ -165,7 +165,7 @@ public async Task Test114( [CombinatorialValues("onclick", "ondblclick", "onmousedown", "onmousemove", "onmouseup")] string eventName, [CombinatorialValues("button", "input", "textarea", "select")] string elementType) { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.EventName, eventName) .Add(p => p.ChildElementType, elementType) .Add(p => p.ChildElementDisabled, false)); @@ -180,7 +180,7 @@ public async Task Test114( [Fact(DisplayName = "TriggerEvent can trigger custom events")] public void Test201() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("input").TriggerEvent("oncustompaste", new CustomPasteEventArgs { @@ -194,7 +194,7 @@ public void Test201() [Fact(DisplayName = "TriggerEventAsync throws NoEventHandlerException when invoked with an unknown event handler ID")] public void Test300() { - var cut = RenderComponent(); + var cut = Render(); var buttons = cut.FindAll("button"); buttons[0].Click(); @@ -204,7 +204,7 @@ public void Test300() [Fact(DisplayName = "Removed bubbled event handled NoEventHandlerException are ignored")] public void Test301() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -220,7 +220,7 @@ public void Test301() [AutoData] public void Test302(string exceptionMessage) { - var cut = RenderComponent(ps => ps.Add(p => p.ExceptionMessage, exceptionMessage)); + var cut = Render(ps => ps.Add(p => p.ExceptionMessage, exceptionMessage)); Should.Throw(() => cut.Find("button").Click()) .Message.ShouldBe(exceptionMessage); @@ -234,7 +234,7 @@ public void Test302(string exceptionMessage) [AutoData] public void Test303(string exceptionMessage) { - var cut = RenderComponent(ps => ps.Add(p => p.ExceptionMessage, exceptionMessage)); + var cut = Render(ps => ps.Add(p => p.ExceptionMessage, exceptionMessage)); Should.Throw(() => cut.Find("button").Click()) .Message.ShouldBe(exceptionMessage); @@ -243,7 +243,7 @@ public void Test303(string exceptionMessage) [Fact(DisplayName = "Should handle click event first and submit form afterwards for button")] public void Test304() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -254,7 +254,7 @@ public void Test304() [Fact(DisplayName = "Should handle click event first and submit form afterwards for input when type button")] public void Test305() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("#inside-form-input").Click(); @@ -265,7 +265,7 @@ public void Test305() [Fact(DisplayName = "Should throw exception when invoking onsubmit from non form")] public void Test306() { - var cut = RenderComponent(); + var cut = Render(); Should.Throw(() => cut.Find("button").Submit()); } @@ -276,7 +276,7 @@ public void Test306() [InlineData("#span-inside-form-button")] public void Test307(string submitElementSelector) { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(x => x.PreventDefault, true)); cut.Find(submitElementSelector).Click(); @@ -294,7 +294,7 @@ public void Test307(string submitElementSelector) [InlineData("#span-inside-form-button-no-handler")] public void Test308(string submitElementSelector) { - var cut = RenderComponent(); + var cut = Render(); cut.Find(submitElementSelector).Click(); @@ -307,7 +307,7 @@ public void Test308(string submitElementSelector) [InlineData("#span-inside-form-button")] public void Test309(string submitElementSelector) { - var cut = RenderComponent(); + var cut = Render(); cut.Find(submitElementSelector).Click(); @@ -322,7 +322,7 @@ public void Test309(string submitElementSelector) [Trait("Category", "async")] public async Task Test400(int repeatCount) { - var cut = RenderComponent(); + var cut = Render(); await cut.WaitForAssertionAsync(() => cut.Find("[data-id=1]")); @@ -339,7 +339,7 @@ public async Task Test400(int repeatCount) [Trait("Category", "sync")] public async Task Test400_Sync(int repeatCount) { - var cut = RenderComponent(); + var cut = Render(); cut.WaitForAssertion(() => cut.Find("[data-id=1]")); diff --git a/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs index 83aea6d77..304c0b8ba 100644 --- a/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs @@ -268,7 +268,7 @@ public void Test124(Cars?[] values) private void VerifyMultipleBindValue(T[] values) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.Options, values)); cut.Find("#bind").Change(values); @@ -282,7 +282,7 @@ private void VerifyMultipleBindValue(T[] values) private void VerifySingleBindValue(T value) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.BindValue, Fixture.Create()) .Add(p => p.OnChangeValue, Fixture.Create()) .Add(p => p.OnInputValue, Fixture.Create())); diff --git a/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs b/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs index 31d40f0ad..d379f0abe 100644 --- a/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs +++ b/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs @@ -11,7 +11,7 @@ public class InputFileTests : TestContext [Fact(DisplayName = "InputFile can upload a single string file")] public void Test001() { - var cut = RenderComponent(); + var cut = Render(); var lastModified = new DateTime(1991, 5, 17); var file = InputFileContent.CreateFromText("Hello World", "Hey.txt", lastModified); @@ -26,7 +26,7 @@ public void Test001() [Fact(DisplayName = "InputFile can upload a single byte file")] public void Test002() { - var cut = RenderComponent(); + var cut = Render(); var file = InputFileContent.CreateFromBinary(Encoding.Default.GetBytes("Hello World")); cut.FindComponent().UploadFiles(file); @@ -37,7 +37,7 @@ public void Test002() [Fact(DisplayName = "InputFile can upload multiple files")] public void Test003() { - var cut = RenderComponent(); + var cut = Render(); var lastModified = new DateTime(1991, 5, 17); var file1 = InputFileContent.CreateFromText("Hello World", "Hey.txt", lastModified, "test"); var file2 = InputFileContent.CreateFromText("World Hey", "Test.txt", lastModified, "unit"); @@ -84,7 +84,7 @@ public void Test006() [Fact(DisplayName = "Upload no files will result in Exception")] public void Test007() { - var cut = RenderComponent(); + var cut = Render(); Action act = () => cut.FindComponent().UploadFiles(); @@ -95,7 +95,7 @@ public void Test007() public void Test008() { JSInterop.SetupVoid("Blazor._internal.InputFile.init").SetException(new Exception()); - var cut = RenderComponent(); + var cut = Render(); Action act = () => cut.FindComponent().UploadFiles(InputFileContent.CreateFromText("Hello")); diff --git a/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs b/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs index 29d1f1714..c26763f7a 100644 --- a/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs +++ b/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs @@ -5,7 +5,7 @@ public class RefreshableQueryCollectionTest : TestContext [Fact(DisplayName = "When the query returns no elements, the collection is empty")] public void Test001() { - var cut = RenderComponent(); + var cut = Render(); var sut = new RefreshableElementCollection(cut, ".foo"); @@ -15,7 +15,7 @@ public void Test001() [Fact(DisplayName = "When the query returns elements, the collection contains those elements")] public void Test002() { - var cut = RenderComponent(); + var cut = Render(); var sut = new RefreshableElementCollection(cut, "h1"); @@ -26,7 +26,7 @@ public void Test002() [Fact(DisplayName = "When Refresh is called, the query is run again and new elements are made available")] public void Test003() { - var cut = RenderComponent(); + var cut = Render(); var sut = new RefreshableElementCollection(cut, "li"); sut.Count.ShouldBe(0); @@ -39,7 +39,7 @@ public void Test003() [Fact(DisplayName = "Enabling auto refresh automatically refreshes query when the rendered fragment renders and has changes")] public void Test004() { - var cut = RenderComponent(); + var cut = Render(); var sut = new RefreshableElementCollection(cut, "li") { EnableAutoRefresh = true }; sut.Count.ShouldBe(0); @@ -51,7 +51,7 @@ public void Test004() [Fact(DisplayName = "Disabling auto refresh turns off automatic refreshing queries on when rendered fragment changes")] public void Test005() { - var cut = RenderComponent(); + var cut = Render(); var sut = new RefreshableElementCollection(cut, "li") { EnableAutoRefresh = true }; sut.EnableAutoRefresh = false; diff --git a/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs b/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs index d7fccaaf6..022b29bd4 100644 --- a/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs +++ b/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs @@ -5,7 +5,7 @@ public class RefreshingWrappedElementTest : TestContext [Fact(DisplayName = "Find() throws when element doesn't exist in DOM")] public void Test001() { - var cut = RenderComponent(ps => ps.Add(p => p.Base, "None")); + var cut = Render(ps => ps.Add(p => p.Base, "None")); Should.Throw(() => cut.Find("div")); } @@ -14,7 +14,7 @@ public void Test001() public void Test010() { var expected = "
    foo
    "; - var cut = RenderComponent(ps => ps.Add(p => p.Base, expected)); + var cut = Render(ps => ps.Add(p => p.Base, expected)); var actual = cut.Find("div"); @@ -25,7 +25,7 @@ public void Test010() public void Test011() { var expected = "
    foo
    "; - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.Base, expected) .Add(p => p.Optional, "
    bar
    ") .Add(p => p.ShowOptional, true)); @@ -38,7 +38,7 @@ public void Test011() [Fact(DisplayName = "Find() refreshes the found element on re-renders")] public void Test020() { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.Base, "
    foo
    ") .Add(p => p.Optional, "
    bar
    ") .Add(p => p.ShowOptional, false)); @@ -48,7 +48,7 @@ public void Test020() // initially only foo div is rendered elm.TextContent.ShouldBe("foo"); - cut.SetParametersAndRender(ps => ps.Add(p => p.ShowOptional, true)); + cut.Render(ps => ps.Add(p => p.ShowOptional, true)); // after optional markup is included, the refreshed query // returns new div as it is now last child @@ -58,7 +58,7 @@ public void Test020() [Fact(DisplayName = "Found element doesn't throw when it's removed from DOM")] public void Test030() { - var cut = RenderComponent(); + var cut = Render(); var btn = cut.Find("button"); @@ -68,7 +68,7 @@ public void Test030() [Fact(DisplayName = "Found element throws when its properties or methods are used after it's removed from DOM")] public void Test031() { - var cut = RenderComponent(); + var cut = Render(); var btn = cut.Find("button"); btn.Click(); // remove from dom diff --git a/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs b/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs index 1c18202f0..1c829cea6 100644 --- a/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs @@ -2,13 +2,13 @@ namespace Bunit; public class RenderedComponentRenderExtensionsTest : TestContext { - [Fact(DisplayName = "SetParametersAndRender rethrows exceptions from SetParameterAsync")] + [Fact(DisplayName = "Render rethrows exceptions from SetParameterAsync")] public void Test001() { - var cut = RenderComponent(); + var cut = Render(); var exception = Should.Throw( - () => cut.SetParametersAndRender(ps => ps.Add(qt => qt.Value, "something"))); + () => cut.Render(ps => ps.Add(qt => qt.Value, "something"))); exception.InnerException.ShouldBeOfType(); } } diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs index 24ab80b0e..68cb1f3fd 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs @@ -17,7 +17,7 @@ public RenderedFragmentWaitForElementsHelperExtensionsAsyncTest(ITestOutputHelpe public async Task Test001() { var expectedMarkup = "

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elm = await cut.WaitForElementAsync("main > p"); @@ -28,7 +28,7 @@ public async Task Test001() [Trait("Category", "async")] public async Task Test002() { - var cut = RenderComponent(); + var cut = Render(); var expected = await Should.ThrowAsync(async () => await cut.WaitForElementAsync("#notHereElm", WaitForTestTimeout)); @@ -41,7 +41,7 @@ public async Task Test002() public async Task Test021() { var expectedMarkup = "

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elms = await cut.WaitForElementsAsync("main > p"); @@ -52,7 +52,7 @@ public async Task Test021() [Trait("Category", "async")] public async Task Test022() { - var cut = RenderComponent(); + var cut = Render(); var expected = await Should.ThrowAsync(async () => await cut.WaitForElementsAsync("#notHereElm", WaitForTestTimeout)); @@ -66,7 +66,7 @@ public async Task Test022() [Trait("Category", "async")] public async Task Test023() { - var cut = RenderComponent(); + var cut = Render(); var expected = await Should.ThrowAsync(async () => await cut.WaitForElementsAsync("#notHereElm", 2, WaitForTestTimeout)); @@ -80,7 +80,7 @@ public async Task Test023() public async Task Test024() { var expectedMarkup = "

    child content

    child content

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elms = await cut.WaitForElementsAsync("main > p", matchElementCount: 3); @@ -92,7 +92,7 @@ public async Task Test024() public async Task Test025() { var expectedMarkup = "

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elms = await cut.WaitForElementsAsync("main > p", matchElementCount: 0); diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs index 98844fc00..5608444a0 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs @@ -17,7 +17,7 @@ public RenderedFragmentWaitForElementsHelperExtensionsTest(ITestOutputHelper tes public void Test001() { var expectedMarkup = "

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elm = cut.WaitForElement("main > p"); @@ -28,7 +28,7 @@ public void Test001() [Trait("Category", "sync")] public void Test002() { - var cut = RenderComponent(); + var cut = Render(); var expected = Should.Throw(() => cut.WaitForElement("#notHereElm", WaitForTestTimeout)); @@ -41,7 +41,7 @@ public void Test002() public void Test021() { var expectedMarkup = "

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elms = cut.WaitForElements("main > p"); @@ -52,7 +52,7 @@ public void Test021() [Trait("Category", "sync")] public void Test022() { - var cut = RenderComponent(); + var cut = Render(); var expected = Should.Throw(() => cut.WaitForElements("#notHereElm", WaitForTestTimeout)); @@ -65,7 +65,7 @@ public void Test022() [Trait("Category", "sync")] public void Test023() { - var cut = RenderComponent(); + var cut = Render(); var expected = Should.Throw(() => cut.WaitForElements("#notHereElm", 2, WaitForTestTimeout)); @@ -79,7 +79,7 @@ public void Test023() public void Test024() { var expectedMarkup = "

    child content

    child content

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elms = cut.WaitForElements("main > p", matchElementCount: 3); @@ -91,7 +91,7 @@ public void Test024() public void Test025() { var expectedMarkup = "

    child content

    "; - var cut = RenderComponent(ps => ps.AddChildContent(expectedMarkup)); + var cut = Render(ps => ps.AddChildContent(expectedMarkup)); var elms = cut.WaitForElements("main > p", matchElementCount: 0); diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs index f4498f4a7..1d079114c 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs @@ -13,7 +13,7 @@ public RenderedFragmentWaitForHelperExtensionsTest(ITestOutputHelper testOutput) public void Test110() { // Initial state is stopped - var cut = RenderComponent(); + var cut = Render(); var stateElement = cut.Find("#state"); stateElement.TextContent.ShouldBe("Stopped"); @@ -30,7 +30,7 @@ public void Test110() [Fact(DisplayName = "WaitForAssertion throws assertion exception after timeout")] public void Test011() { - var cut = RenderComponent(); + var cut = Render(); var expected = Should.Throw(() => cut.WaitForAssertion(() => cut.Markup.ShouldBeEmpty(), TimeSpan.FromMilliseconds(10))); @@ -41,7 +41,7 @@ public void Test011() [Fact(DisplayName = "WaitForState throws exception after timeout")] public void Test012() { - var cut = RenderComponent(); + var cut = Render(); var expected = Should.Throw(() => cut.WaitForState(() => string.IsNullOrEmpty(cut.Markup), TimeSpan.FromMilliseconds(100))); @@ -53,7 +53,7 @@ public void Test012() public void Test013() { const string expectedInnerMessage = "INNER MESSAGE"; - var cut = RenderComponent(); + var cut = Render(); cut.Find("#tick").Click(); cut.Find("#tock").Click(); @@ -74,7 +74,7 @@ public void Test013() public void Test100() { // Initial state is stopped - var cut = RenderComponent(); + var cut = Render(); // Clicking 'tick' changes the state, and starts a task cut.Find("#tick").Click(); @@ -93,7 +93,7 @@ public void Test100() [Fact(DisplayName = "WaitForState can detect async changes to properties in the CUT")] public void Test200() { - var cut = RenderComponent(); + var cut = Render(); cut.Instance.Counter.ShouldBe(0); // Clicking 'tick' changes the counter, and starts a task @@ -111,7 +111,7 @@ public void Test200() [Fact(DisplayName = "WaitForAssertion rethrows unhandled exception from a components async operation's methods")] public void Test300() { - var cut = RenderComponent(); + var cut = Render(); // Adding additional wait time to deal with tests sometimes failing for timeout on Windows. Should.Throw( @@ -121,7 +121,7 @@ public void Test300() [Fact(DisplayName = "WaitForState rethrows unhandled exception from components async operation's methods")] public void Test301() { - var cut = RenderComponent(); + var cut = Render(); // Adding additional wait time to deal with tests sometimes failing for timeout on Windows. Should.Throw( diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs index 709a78ff5..fd916a89d 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs @@ -5,7 +5,7 @@ public class FocusAsyncInvocationHandlerTest : TestContext [Fact(DisplayName = "Can render components that calls FocusAsync")] public void Test001() { - var cut = RenderComponent(); + var cut = Render(); var input = cut.Find("input"); JSInterop.VerifyFocusAsyncInvoke().Arguments[0].ShouldBeElementReferenceTo(input); } @@ -13,7 +13,7 @@ public void Test001() [Fact(DisplayName = "Can capture two FocusAsync calls")] public void Test002() { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .AddChildContent() .AddChildContent()); @@ -27,7 +27,7 @@ public void Test002() [Fact(DisplayName = "Will return completed task")] public void Test003() { - var cut = RenderComponent(); + var cut = Render(); Assert.True(cut.Instance.AfterFirstRender); } diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs index f641b2601..6bcffec35 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs @@ -6,7 +6,7 @@ public class FocusOnNavigateHandlerTest : TestContext public void Test001() { // - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.FoundTemplate, routeData => cps => cps .Add(x => x.RouteData, routeData) .Add(x => x.Selector, "h1"))); @@ -22,7 +22,7 @@ public void Test001() [Fact(DisplayName = "Will return completed task")] public void Test002() { - var cut = RenderComponent(ps => ps + var cut = Render(ps => ps .Add(p => p.FoundTemplate, routeData => cps => cps .Add(x => x.RouteData, routeData) .Add(x => x.Selector, "h1"))); diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs index a097d16f5..1522c4611 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs @@ -13,7 +13,7 @@ public class VirtualizeJSRuntimeInvocationHandlerTest : TestContext [MemberData(nameof(ItemsInCollection))] public void Test001(int itemsInDataSource) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.Items, CreateItems(itemsInDataSource)) .Add(p => p.ChildContent, item => $"

    {item}

    ")); @@ -24,7 +24,7 @@ public void Test001(int itemsInDataSource) [MemberData(nameof(ItemsInCollection))] public void Test002(int itemsInDataSource) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.Items, CreateItems(itemsInDataSource)) .Add(p => p.ItemContent, item => $"

    {item}

    ")); @@ -35,7 +35,7 @@ public void Test002(int itemsInDataSource) [MemberData(nameof(ItemsInCollection))] public void Test010(int itemsInDataSource) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) .Add(p => p.ChildContent, item => $"

    {item}

    ")); @@ -46,7 +46,7 @@ public void Test010(int itemsInDataSource) [MemberData(nameof(ItemsInCollection))] public void Test011(int itemsInDataSource) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) .Add(p => p.ItemContent, item => $"

    {item}

    ")); @@ -68,7 +68,7 @@ public void Test011(int itemsInDataSource) [MemberData(nameof(ItemCountItemSizeOverscanCount))] public void Test030(int itemsInDataSource, float itemSize, int overscanCount) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.ItemsProvider, CreateItemsProvider(itemsInDataSource)) .Add(p => p.ItemContent, item => $"

    {item}

    ") .Add(p => p.ItemSize, itemSize) @@ -81,7 +81,7 @@ public void Test030(int itemsInDataSource, float itemSize, int overscanCount) [MemberData(nameof(ItemsInCollection))] public void Test040(int itemsInDataSource) { - var cut = RenderComponent>(ps => ps + var cut = Render>(ps => ps .Add(p => p.ItemsProvider, _ => ValueTask.FromResult(new ItemsProviderResult(Array.Empty(), itemsInDataSource))) .Add(p => p.ItemContent, item => @$"

    {item}

    ") .Add(p => p.Placeholder, _ => @"

    ")); diff --git a/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs b/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs index ce54ecf5d..88332b291 100644 --- a/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs +++ b/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs @@ -10,7 +10,7 @@ public void Test001() var activator = new CustomComponentActivator(); Services.AddSingleton(activator); - var cut = RenderComponent(); + var cut = Render(); cut.Instance.ShouldBeOfType(); } @@ -21,7 +21,7 @@ public void Test002() var activator = new CustomComponentActivator(); Services.AddSingleton(activator); - RenderComponent(); + Render(); activator.RequestedComponentTypes .ShouldHaveSingleItem() @@ -35,7 +35,7 @@ public void Test003() Services.AddSingleton(activator); ComponentFactories.AddStub(); - var cut = RenderComponent(ps => ps.AddChildContent()); + var cut = Render(ps => ps.AddChildContent()); activator.RequestedComponentTypes .ShouldHaveSingleItem() diff --git a/tests/bunit.tests/Rendering/BunitRendererBunit.cs b/tests/bunit.tests/Rendering/BunitRendererBunit.cs index f28c37e2b..37c204bcf 100644 --- a/tests/bunit.tests/Rendering/BunitRendererBunit.cs +++ b/tests/bunit.tests/Rendering/BunitRendererBunit.cs @@ -23,12 +23,12 @@ public void Test004() .Message.ShouldBe(ThrowsDuringSetParams.EXCEPTION.Message); } - [Fact(DisplayName = "RenderComponent re-throws exception from component")] + [Fact(DisplayName = "Render re-throws exception from component")] public void Test003() { using var sut = CreateRenderer(); - Should.Throw(() => sut.RenderComponent()) + Should.Throw(() => sut.Render()) .Message.ShouldBe(ThrowsDuringSetParams.EXCEPTION.Message); } @@ -49,7 +49,7 @@ public void Test002() { using var sut = CreateRenderer(); - var cut = sut.RenderComponent(); + var cut = sut.Render(); cut.RenderCount.ShouldBe(1); cut.Markup.ShouldBe(NoChildNoParams.MARKUP); @@ -62,7 +62,7 @@ public void Test005() const string VALUE = "FOO BAR"; using var sut = CreateRenderer(); - var cut = sut.RenderComponent((nameof(HasParams.Value), VALUE)); + var cut = sut.Render((nameof(HasParams.Value), VALUE)); cut.Instance.Value.ShouldBe(VALUE); } @@ -75,7 +75,7 @@ public void Test006() using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( (nameof(HasParams.Value), PARENT_VALUE), ChildContent((nameof(HasParams.Value), CHILD_VALUE))); @@ -88,7 +88,7 @@ public async Task Test010() { using var sut = CreateRenderer(); - var cut = sut.RenderComponent(); + var cut = sut.Render(); cut.RenderCount.ShouldBe(1); @@ -103,7 +103,7 @@ public async Task Test011() // arrange const string EXPECTED = "NOW VALUE"; using var sut = CreateRenderer(); - var cut = sut.RenderComponent(); + var cut = sut.Render(); cut.RenderCount.ShouldBe(1); @@ -124,7 +124,7 @@ public void Test020() using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( (nameof(HasParams.Value), PARENT_VALUE), ChildContent((nameof(HasParams.Value), CHILD_VALUE))); @@ -148,7 +148,7 @@ public void Test021() public void Test022() { using var sut = CreateRenderer(); - var cut = sut.RenderComponent(); + var cut = sut.Render(); Should.Throw(() => sut.FindComponent(cut)); } @@ -158,7 +158,7 @@ public void Test023() { using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( ChildContent()); var child1 = sut.FindComponent(cut); @@ -177,7 +177,7 @@ public void Test030() using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( (nameof(HasParams.Value), GRAND_PARENT_VALUE), ChildContent( (nameof(HasParams.Value), PARENT_VALUE), @@ -210,7 +210,7 @@ public void Test032() { // arrange using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( ChildContent( ChildContent())); @@ -227,7 +227,7 @@ public async Task Test040() { using var sut = CreateRenderer(); - var parent = sut.RenderComponent( + var parent = sut.Render( ChildContent()); // act @@ -246,7 +246,7 @@ public async Task Test041() { using var sut = CreateRenderer(); - var parent = sut.RenderComponent( + var parent = sut.Render( ChildContent()); // act @@ -266,7 +266,7 @@ public async Task Test050() // arrange using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( ChildContent()); var child = sut.FindComponent(cut); @@ -284,7 +284,7 @@ public async Task Test060() // arrange using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( ChildContent()); var child = sut.FindComponent(cut); @@ -302,7 +302,7 @@ public async Task Test061() // arrange using var sut = CreateRenderer(); - var cut = sut.RenderComponent( + var cut = sut.Render( ChildContent( ChildContent())); var child = sut.FindComponent(cut); @@ -320,7 +320,7 @@ public async Task Test061() public void Test070() { var sut = CreateRenderer(); - var cut = sut.RenderComponent(); + var cut = sut.Render(); sut.Dispose(); @@ -332,7 +332,7 @@ public void Test100() { var tcs = new TaskCompletionSource(); - var cut = RenderComponent(parameters => + var cut = Render(parameters => parameters.Add(p => p.EitherOr, tcs.Task)); cut.Find("h1").TextContent.ShouldBe("FIRST"); @@ -342,7 +342,7 @@ public void Test100() [Trait("Category", "async")] public async Task Test101() { - var cut = RenderComponent(parameters => + var cut = Render(parameters => parameters.Add(p => p.EitherOr, Task.Delay(1))); await cut.WaitForAssertionAsync(() => cut.Find("h1").TextContent.ShouldBe("SECOND")); @@ -352,7 +352,7 @@ public async Task Test101() [Trait("Category", "sync")] public void Test101_Sync() { - var cut = RenderComponent(parameters => + var cut = Render(parameters => parameters.Add(p => p.EitherOr, Task.Delay(1))); cut.WaitForAssertion(() => cut.Find("h1").TextContent.ShouldBe("SECOND")); @@ -361,7 +361,7 @@ public void Test101_Sync() [Fact(DisplayName = "Can render component that awaits completed task in OnInitializedAsync")] public void Test102() { - var cut = RenderComponent(parameters => + var cut = Render(parameters => parameters.Add(p => p.EitherOr, Task.CompletedTask)); cut.Find("h1").TextContent.ShouldBe("SECOND"); @@ -371,7 +371,7 @@ public void Test102() public async Task Test200() { var syncException = Should.Throw( - () => RenderComponent()); + () => Render()); var capturedException = await Renderer.UnhandledException; capturedException.ShouldBe(syncException); @@ -382,7 +382,7 @@ public async Task Test201() { var tsc = new TaskCompletionSource(); var expectedException = new AsyncOperationThrows.AsyncOperationThrowsException(); - RenderComponent(ps => ps.Add(p => p.Awaitable, tsc.Task)); + Render(ps => ps.Add(p => p.Awaitable, tsc.Task)); tsc.SetException(expectedException); @@ -394,14 +394,14 @@ public async Task Test201() public async Task Test202() { var tsc1 = new TaskCompletionSource(); - RenderComponent(ps => ps.Add(p => p.Awaitable, tsc1.Task)); + Render(ps => ps.Add(p => p.Awaitable, tsc1.Task)); tsc1.SetException(new AsyncOperationThrows.AsyncOperationThrowsException()); var firstExceptionReported = await Renderer.UnhandledException; var secondException = new AsyncOperationThrows.AsyncOperationThrowsException(); var tsc2 = new TaskCompletionSource(); - RenderComponent(ps => ps.Add(p => p.Awaitable, tsc2.Task)); + Render(ps => ps.Add(p => p.Awaitable, tsc2.Task)); tsc2.SetException(secondException); var secondExceptionReported = await Renderer.UnhandledException; @@ -414,7 +414,7 @@ public async Task Test203() { // Arrange var planned = JSInterop.SetupVoid("foo"); - RenderComponent(); + Render(); // Act planned.SetVoidResult(); // <-- After here the `OnAfterRenderAsync` progresses and throws an exception. @@ -424,20 +424,10 @@ public async Task Test203() (await Renderer.UnhandledException).ShouldBeOfType(); } - [Fact(DisplayName = "Multiple calls to StateHasChanged from OnParametersSet with SetParametersAndRender")] - public void Test204() - { - var cut = RenderComponent(); - cut.RenderCount.ShouldBe(1); - - cut.SetParametersAndRender(); - cut.RenderCount.ShouldBe(2); - } - [Fact(DisplayName = "Multiple calls to StateHasChanged from OnParametersSet with Render")] public void Test205() { - var cut = RenderComponent(); + var cut = Render(); cut.RenderCount.ShouldBe(1); cut.Render(); @@ -447,7 +437,7 @@ public void Test205() [Fact(DisplayName = "Multiple calls to StateHasChanged from OnParametersSet with event dispatch render trigger")] public void Test206() { - var cut = RenderComponent(); + var cut = Render(); var child = cut.FindComponent(); child.RenderCount.ShouldBe(1); @@ -459,7 +449,7 @@ public void Test206() [Fact(DisplayName = "Multiple calls to StateHasChanged from OnParametersSet with Render")] public void Test207() { - var cut = RenderComponent(); + var cut = Render(); cut.RenderCount.ShouldBe(1); cut.Render(); @@ -473,27 +463,10 @@ public void Test207() cut.Instance.AfterRenderAsyncCount.ShouldBe(2); } - [Fact(DisplayName = "Multiple calls to StateHasChanged from OnParametersSet with Render")] - public void Test208() - { - var cut = RenderComponent(); - cut.RenderCount.ShouldBe(1); - - cut.SetParametersAndRender(); - - cut.RenderCount.ShouldBe(2); - cut.Instance.InitilizedCount.ShouldBe(1); - cut.Instance.InitilizedAsyncCount.ShouldBe(1); - cut.Instance.ParametersSetCount.ShouldBe(2); - cut.Instance.ParametersSetAsyncCount.ShouldBe(2); - cut.Instance.AfterRenderCount.ShouldBe(2); - cut.Instance.AfterRenderAsyncCount.ShouldBe(2); - } - [Fact(DisplayName = "Can render components that have a RenderMode InteractiveAuto")] public void Test209() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveAuto}"); } @@ -501,7 +474,7 @@ public void Test209() [Fact(DisplayName = "Can render components that have a RenderMode InteractiveServer")] public void Test210() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveServer}"); } @@ -509,11 +482,11 @@ public void Test210() [Fact(DisplayName = "Can render components that have a RenderMode InteractiveWebAssembly")] public void Test211() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveWebAssembly}"); } - + [Fact(DisplayName = "given a IComponentActivator, " + "when passed to constructor," + "then it used to create components")] @@ -527,7 +500,7 @@ public void Test1000() NullLoggerFactory.Instance, activatorMock); - renderer.RenderComponent(new ComponentParameterCollection()); + renderer.Render(new ComponentParameterCollection()); activatorMock.Received(1).CreateInstance(typeof(Wrapper)); } diff --git a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs index ee2519a85..0ef853158 100644 --- a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs +++ b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs @@ -8,7 +8,7 @@ public partial class HtmlizerTests : TestContext [InlineData(true, true)] public void Test002(bool stopPropagation, bool preventDefault) { - var component = RenderComponent(parameters => parameters + var component = Render(parameters => parameters .Add(p => p.OnClick, _ => { }) .Add(p => p.OnClickStopPropagation, stopPropagation) .Add(p => p.OnClickPreventDefault, preventDefault)); @@ -22,7 +22,7 @@ public void Test002(bool stopPropagation, bool preventDefault) [Fact(DisplayName = "Blazor ElementReferences are included in rendered markup")] public void Test001() { - var cut = RenderComponent(); + var cut = Render(); var elmRefValue = cut.Find("button").GetAttribute("blazor:elementreference"); @@ -32,10 +32,10 @@ public void Test001() [Fact(DisplayName = "Blazor ElementReferences start in markup on rerenders")] public void Test003() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").HasAttribute("blazor:elementreference").ShouldBeTrue(); - cut.SetParametersAndRender(parameters => parameters.Add(p => p.OnClick, _ => { })); + cut.Render(parameters => parameters.Add(p => p.OnClick, _ => { })); cut.Find("button").HasAttribute("blazor:elementreference").ShouldBeTrue(); } diff --git a/tests/bunit.tests/Rendering/RenderedComponentTest.cs b/tests/bunit.tests/Rendering/RenderedComponentTest.cs index a4dd4a0d9..ece1dd8c6 100644 --- a/tests/bunit.tests/Rendering/RenderedComponentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedComponentTest.cs @@ -7,7 +7,7 @@ public class RenderedComponentTest : TestContext [Fact(DisplayName = "Call to Render() results in a render of component")] public void Test001() { - var cut = RenderComponent(parameters => parameters.AddChildContent("
    ")); + var cut = Render(parameters => parameters.AddChildContent("
    ")); var initialRenderCount = cut.RenderCount; cut.Render(); @@ -15,45 +15,45 @@ public void Test001() cut.RenderCount.ShouldBe(initialRenderCount + 1); } - [Fact(DisplayName = "Call to SetParametersAndRender(builder) provides the parameters to component")] + [Fact(DisplayName = "Call to Render(builder) provides the parameters to component")] public void Test004() { - var cut = RenderComponent(parameters => parameters.AddChildContent("
    ")); + var cut = Render(parameters => parameters.AddChildContent("
    ")); - cut.SetParametersAndRender(parameters => parameters.AddChildContent("

    ")); + cut.Render(parameters => parameters.AddChildContent("

    ")); cut.Find("p").ShouldNotBeNull(); } - [Fact(DisplayName = "Call to SetParametersAndRender(params) provides the parameters to component")] + [Fact(DisplayName = "Call to Render(params) provides the parameters to component")] public void Test0041() { - var cut = RenderComponent(parameters => parameters.AddChildContent("

    ")); + var cut = Render(parameters => parameters.AddChildContent("
    ")); - cut.SetParametersAndRender(ComponentParameterFactory.ChildContent("

    ")); + cut.Render(ComponentParameterFactory.ChildContent("

    ")); cut.Find("p").ShouldNotBeNull(); } - [Fact(DisplayName = "Trying to set CascadingValue during SetParametersAndRender throws")] + [Fact(DisplayName = "Trying to set CascadingValue during Render throws")] public void Test003() { // arrange - var cut = RenderComponent>(); + var cut = Render>(); // assert - Should.Throw(() => cut.SetParametersAndRender(ps => ps.Add(p => p.UnnamedCascadingValue, 42))); - Should.Throw(() => cut.SetParametersAndRender(ps => ps.Add(p => p.NamedCascadingValue, 1337))); + Should.Throw(() => cut.Render(ps => ps.Add(p => p.UnnamedCascadingValue, 42))); + Should.Throw(() => cut.Render(ps => ps.Add(p => p.NamedCascadingValue, 1337))); } [Fact(DisplayName = "Getting Instance from a RenderedComponent based on a disposed component throws")] public void Test020() { - var cut = RenderComponent(ps => ps.Add(p => p.ShowChild, true)); + var cut = Render(ps => ps.Add(p => p.ShowChild, true)); var target = cut.FindComponent(); // Disposes of - cut.SetParametersAndRender(ps => ps.Add(p => p.ShowChild, false)); + cut.Render(ps => ps.Add(p => p.ShowChild, false)); Should.Throw(() => target.Instance); } diff --git a/tests/bunit.tests/Rendering/RenderedFragmentTest.cs b/tests/bunit.tests/Rendering/RenderedFragmentTest.cs index cd9cce7da..a03d889a9 100644 --- a/tests/bunit.tests/Rendering/RenderedFragmentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedFragmentTest.cs @@ -12,14 +12,14 @@ public RenderedFragmentTest(ITestOutputHelper output) [Fact(DisplayName = "Find throws an exception if no element matches the css selector")] public void Test001() { - var cut = RenderComponent(); + var cut = Render(); Should.Throw(() => cut.Find("div")); } [Fact(DisplayName = "Find returns expected element that matches the css selector")] public void Test002() { - var cut = RenderComponent(x => x.AddChildContent("

    ")); + var cut = Render(x => x.AddChildContent("
    ")); var result = cut.Find("div"); result.ShouldNotBeNull(); } @@ -28,7 +28,7 @@ public void Test002() "when a event handler trigger has caused changes to DOM tree")] public void Test006() { - var cut = RenderComponent(); + var cut = Render(); var initialNodes = cut.Nodes; cut.Find("button").Click(); @@ -40,7 +40,7 @@ public void Test006() "when a nested component has caused the DOM tree to change")] public void Test007() { - var cut = RenderComponent>(builder => builder + var cut = Render>(builder => builder .Add(p => p.Value, "FOO") .AddChildContent()); @@ -55,7 +55,7 @@ public void Test007() "when a re-render does not causes the DOM to change")] public void Test008() { - var cut = RenderComponent(); + var cut = Render(); var initialNodes = cut.Nodes; cut.Find("button").Click(); @@ -67,12 +67,12 @@ public void Test008() [Fact(DisplayName = "Changes to event handler should return a new instance of DOM tree")] public void Test009() { - var cut = RenderComponent(); + var cut = Render(); cut.Find("#btn").Click(); cut.Instance.Counter.ShouldBe(1); - cut.SetParametersAndRender((nameof(ToggleClickHandler.HandleClicks), false)); + cut.Render((nameof(ToggleClickHandler.HandleClicks), false)); cut.Find("#btn").Click(); @@ -82,7 +82,7 @@ public void Test009() [Fact(DisplayName = "FindComponent returns component from first branch of tree in first depth first search")] public void Test100() { - var wrapper = RenderComponent(builder => builder + var wrapper = Render(builder => builder .Add(p => p.First, wrapper => wrapper .AddChildContent(simple1 => simple1 .Add(p => p.Header, "First"))) @@ -97,7 +97,7 @@ public void Test100() [Fact(DisplayName = "FindComponent finds components when first tree branch is empty")] public void Test101() { - var wrapper = RenderComponent(builder => builder + var wrapper = Render(builder => builder .Add(p => p.First) .Add(p => p.Second, simple1 => simple1 .Add(p => p.Header, "Second"))); @@ -110,7 +110,7 @@ public void Test101() [Fact(DisplayName = "GetComponent throws when component of requested type is not in the render tree")] public void Test102() { - var wrapper = RenderComponent(); + var wrapper = Render(); Should.Throw(() => wrapper.FindComponent()); } @@ -118,7 +118,7 @@ public void Test102() [Fact(DisplayName = "GetComponents returns all components of requested type using a depth first order")] public void Test103() { - var wrapper = RenderComponent(builder => builder + var wrapper = Render(builder => builder .Add(p => p.First, wrapper => wrapper .AddChildContent(simple1 => simple1 .Add(p => p.Header, "First"))) @@ -135,7 +135,7 @@ public void Test103() [Fact(DisplayName = "Render events for non-rendered sub components are not emitted")] public void Test010() { - var wrapper = RenderComponent(parameters => parameters + var wrapper = Render(parameters => parameters .Add(p => p.First) .Add(p => p.Second)); var cuts = wrapper.FindComponents(); @@ -162,11 +162,11 @@ public void Test010() [Fact(DisplayName = "Getting Markup from a RenderedFragment based on a disposed component throws")] public void Test020() { - var cut = RenderComponent(ps => ps.Add(p => p.ShowChild, true)); + var cut = Render(ps => ps.Add(p => p.ShowChild, true)); var target = cut.FindComponent(); // Disposes of - cut.SetParametersAndRender(ps => ps.Add(p => p.ShowChild, false)); + cut.Render(ps => ps.Add(p => p.ShowChild, false)); Should.Throw(() => target.Markup); } diff --git a/tests/bunit.tests/Rendering/RootRenderTreeTest.cs b/tests/bunit.tests/Rendering/RootRenderTreeTest.cs index f874ee365..8276809d5 100644 --- a/tests/bunit.tests/Rendering/RootRenderTreeTest.cs +++ b/tests/bunit.tests/Rendering/RootRenderTreeTest.cs @@ -34,7 +34,7 @@ public void Test100() Should.Throw(() => { RenderTree.Add(); - RenderComponent(); + Render(); }); } @@ -43,7 +43,7 @@ public void Test110() { RenderTree.Add(); - var cut = RenderComponent(); + var cut = Render(); cut.Markup.ShouldBe("
    LAYOUT VALUE
    "); } @@ -53,7 +53,7 @@ public void Test111() { RenderTree.Add(parameters => parameters.Add(p => p.Value, "ANOTHER VALUE")); - var cut = RenderComponent(); + var cut = Render(); cut.Markup.ShouldBe("
    ANOTHER VALUE
    "); } @@ -64,12 +64,12 @@ public void Test112() RenderTree.Add>(parameters => parameters.Add(p => p.Value, "VALUE")); RenderTree.Add>(parameters => parameters.Add(p => p.Value, 42)); - var cut = RenderComponent(); + var cut = Render(); cut.Markup.ShouldBe("
    VALUE42
    "); } - [Fact(DisplayName = "RenderComponent finds correct component when T is also added to render tree")] + [Fact(DisplayName = "Render finds correct component when T is also added to render tree")] public void Test113() { RenderTree.Add>(parameters => parameters.Add(p => p.Value, "VALUE")); @@ -77,18 +77,18 @@ public void Test113() RenderTree.Add>(parameters => parameters.Add(p => p.Value, 42)); RenderTree.Add(); - var cut = RenderComponent(); + var cut = Render(); cut.Markup.ShouldBe("
    VALUE42
    "); } - [Fact(DisplayName = "RenderComponent finds correct component when T is also added to render tree")] + [Fact(DisplayName = "Render finds correct component when T is also added to render tree")] public void Test113_2() { RenderTree.Add>(parameters => parameters.Add(p => p.Value, "VALUE")); RenderTree.Add>(parameters => parameters.Add(p => p.Value, 42)); - var cut = RenderComponent>(parameters => parameters + var cut = Render>(parameters => parameters .Add(p => p.Value, "FOO")); cut.Instance.Value.ShouldBe("FOO"); @@ -100,7 +100,7 @@ public void Test114() RenderTree.Add(parameters => parameters.Add(p => p.Value, "FOO")); RenderTree.Add(parameters => parameters.Add(p => p.Value, "BAR")); - var cut = RenderComponent(); + var cut = Render(); cut.Markup.ShouldBe($"
    BAR
    "); } @@ -111,7 +111,7 @@ public void Test120() RenderTree.Add(parameters => parameters.Add(p => p.Value, "FOO")); RenderTree.TryAdd(parameters => parameters.Add(p => p.Value, "BAR")); - var cut = RenderComponent(); + var cut = Render(); cut.Markup.ShouldBe("
    FOO
    "); } diff --git a/tests/bunit.tests/TestContextTest.cs b/tests/bunit.tests/TestContextTest.cs index 86049d7b9..0363670b0 100644 --- a/tests/bunit.tests/TestContextTest.cs +++ b/tests/bunit.tests/TestContextTest.cs @@ -9,7 +9,7 @@ public partial class TestContextTest : TestContext public void Test101() { var callStack = new List(); - RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); + Render(ps => ps.Add(p => p.CallStack, callStack)); DisposeComponents(); @@ -22,8 +22,8 @@ public void Test101() public void Test102() { var callStack = new List(); - RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); - RenderComponent(ps => ps.Add(p => p.CallStack, callStack)); + Render(ps => ps.Add(p => p.CallStack, callStack)); + Render(ps => ps.Add(p => p.CallStack, callStack)); DisposeComponents(); @@ -33,7 +33,7 @@ public void Test102() [Fact(DisplayName = "DisposeComponents rethrows exceptions from Dispose methods in components")] public void Test103() { - RenderComponent(); + Render(); var action = () => DisposeComponents(); action.ShouldThrow(); @@ -49,17 +49,17 @@ public void Test104() callStack.Count.ShouldBe(1); } - + [Fact(DisplayName = "The test service provider should register a placeholder HttpClient which throws exceptions")] public void Test024() { - Should.Throw(() => RenderComponent()); + Should.Throw(() => Render()); } [Fact(DisplayName = "The test service provider should register a placeholder IStringLocalizer which throws exceptions")] public void Test026() { - Should.Throw(() => RenderComponent()); + Should.Throw(() => Render()); } [Fact(DisplayName = "Render() renders fragment inside RenderTree")] @@ -93,22 +93,22 @@ public void Test031() .ShouldBe("FOO"); } - [Fact(DisplayName = "RenderComponent(builder) renders TComponent inside RenderTreee")] + [Fact(DisplayName = "Render(builder) renders TComponent inside RenderTreee")] public void Test032() { RenderTree.Add>(ps => ps.Add(p => p.Value, "FOO")); - var cut = RenderComponent(ps => ps.Add(p => p.Dummy, null)); + var cut = Render(ps => ps.Add(p => p.Dummy, null)); cut.Instance .Value .ShouldBe("FOO"); } - [Fact(DisplayName = "RenderComponent(factories) renders TComponent inside RenderTreee")] + [Fact(DisplayName = "Render(factories) renders TComponent inside RenderTreee")] public void Test033() { RenderTree.Add>(ps => ps.Add(p => p.Value, "FOO")); - var cut = RenderComponent(("Dummy", null)); + var cut = Render(("Dummy", null)); cut.Instance .Value @@ -118,23 +118,23 @@ public void Test033() [Fact(DisplayName = "Can raise events from markup rendered with TestContext")] public void Test040() { - Should.NotThrow(() => RenderComponent().Find("button").Click()); + Should.NotThrow(() => Render().Find("button").Click()); } - + [Fact(DisplayName = "TestContext should provide a default IErrorBoundaryLogger")] public void Test001() { IErrorBoundaryLogger logger = Services.GetService(); logger.ShouldNotBe(null); } - + [Fact(DisplayName = "ComponentFactories CanCreate() method are checked during component instantiation")] public void Test0001() { var mock = CreateMockComponentFactory(canCreate: _ => false, create: _ => null); ComponentFactories.Add(mock); - RenderComponent(); + Render(); mock.Received(1).CanCreate(typeof(Simple1)); mock.DidNotReceive().Create(Arg.Any()); @@ -146,7 +146,7 @@ public void Test0002() var mock = CreateMockComponentFactory(canCreate: _ => true, create: _ => new Simple1()); ComponentFactories.Add(mock); - RenderComponent(); + Render(); mock.Received(1).CanCreate(typeof(Simple1)); mock.Received(1).Create(typeof(Simple1)); @@ -160,7 +160,7 @@ public void Test0003() ComponentFactories.Add(firstMock); ComponentFactories.Add(secondMock); - RenderComponent(); + Render(); firstMock.DidNotReceive().CanCreate(Arg.Any()); firstMock.DidNotReceive().Create(Arg.Any()); @@ -173,7 +173,7 @@ public async Task Test201() { var tcs = new TaskCompletionSource(); var expected = new NotSupportedException(); - RenderComponent( + Render( ps => ps.Add(p => p.DisposedTask, tcs.Task)); DisposeComponents(); @@ -186,7 +186,7 @@ public async Task Test201() [Fact(DisplayName = "DisposeComponents calls DisposeAsync on rendered components")] public async Task Test202() { - var cut = RenderComponent(); + var cut = Render(); var wasDisposedTask = cut.Instance.DisposedTask; DisposeComponents(); @@ -198,7 +198,7 @@ public async Task Test202() public void Test203() { ComponentFactories.Add(); - var cut = RenderComponent(ps => ps.Add(p => p.CallStack, new List())); + var cut = Render(ps => ps.Add(p => p.CallStack, new List())); var instance = cut.FindComponent().Instance; DisposeComponents(); @@ -248,7 +248,7 @@ private sealed class ReceivesCascadingValue : ComponentBase [Parameter] public object? Dummy { get; set; } } - + private sealed class ThrowExceptionComponent : ComponentBase, IDisposable { public void Dispose() @@ -258,7 +258,7 @@ public void Dispose() #pragma warning restore S3877 } } - + private sealed class AsyncDisposableService : IAsyncDisposable { public bool IsDisposed { get; private set; } diff --git a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs index 95acc7bff..f7f66e4c3 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs @@ -17,7 +17,7 @@ public void Test001() this.AddAuthorization(); // Act - var cut = RenderComponent(); + var cut = Render(); // Assert cut.MarkupMatches("Not authorized?"); @@ -31,7 +31,7 @@ public void Test002() authContext.SetAuthorized("TestUser", AuthorizationState.Authorized); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches("Authorized!"); @@ -45,7 +45,7 @@ public void Test003() authContext.SetAuthorized("TestUser", AuthorizationState.Unauthorized); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches("Not authorized?"); @@ -59,7 +59,7 @@ public async Task Test004() var authContext = this.AddAuthorization(); // start off unauthenticated. - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches("Not authorized?"); // act @@ -79,7 +79,7 @@ public void Test004_Sync() var authContext = this.AddAuthorization(); // start off unauthenticated. - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches("Not authorized?"); // act @@ -99,7 +99,7 @@ public void Test005() authContext.SetAuthorized("TestUser005", AuthorizationState.Authorized); // start off unauthenticated. - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches("Authorized!"); // act @@ -115,7 +115,7 @@ public void Test005() public void Test006() { // act - var ex = Assert.Throws(() => RenderComponent()); + var ex = Assert.Throws(() => Render()); // assert Assert.Equal("AuthenticationStateProvider", ex.ServiceName); @@ -130,7 +130,7 @@ public void Test007() authContext.SetAuthorized("TestUser").SetPolicies("ContentViewer"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches("Authorized for content viewers."); @@ -144,7 +144,7 @@ public void Test008() authContext.SetAuthorized("TestUser"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(string.Empty); @@ -158,7 +158,7 @@ public void Test0081() authContext.SetAuthorized("TestUser").SetPolicies("OtherPolicy"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(string.Empty); @@ -172,7 +172,7 @@ public void Test009() authContext.SetAuthorized("TestUser").SetRoles("Admin"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches("Authorized content for admins."); @@ -186,7 +186,7 @@ public void Test010() authContext.SetAuthorized("TestUser"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(string.Empty); @@ -200,7 +200,7 @@ public void Test011() authContext.SetAuthorized("TestUser").SetRoles("NotAdmin"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(string.Empty); @@ -214,7 +214,7 @@ public void Test012() authContext.SetAuthorizing(); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches("Authorizing..."); @@ -231,7 +231,7 @@ public void Test013() authContext.SetAuthorized("TestUser").SetClaims(uuidClaim, emailClaim); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(@$"
    Authorized!
    @@ -248,7 +248,7 @@ public void Test014() authContext.SetAuthorized("TestUser"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(@"
    Authorized!
    @@ -263,7 +263,7 @@ public void Test020() authCtx.SetAuthorized("FooBar"); authCtx.SetRoles(role); - var cut = RenderComponent(ps => ps.Add(p => p.ExpectedRole, role)); + var cut = Render(ps => ps.Add(p => p.ExpectedRole, role)); cut.MarkupMatches("

    True

    "); } @@ -277,7 +277,7 @@ public void Test021() authContext.SetAuthenticationType("custom-auth-type"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches("

    Authorized content with custom auth type.

    "); @@ -291,7 +291,7 @@ public void Test022() authContext.SetAuthorized("TestUser"); // act - var cut = RenderComponent(); + var cut = Render(); // assert cut.MarkupMatches(string.Empty); diff --git a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs index 865a57bcf..7c3c1a038 100644 --- a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs @@ -6,7 +6,7 @@ public class BunitSignOutSessionStateManagerTest : TestContext public void ShouldSignOut(string randomUserName) { this.AddAuthorization().SetAuthorized(randomUserName); - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); diff --git a/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs b/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs index 182023b4f..2e92ebc32 100644 --- a/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs @@ -8,7 +8,7 @@ public void ShouldSayHelloToDevelopers() var hostEnvironment = Services.GetRequiredService(); hostEnvironment.SetEnvironmentToDevelopment(); - var cut = RenderComponent(); + var cut = Render(); // Assert - inspects markup to verify the message cut.Find("p").MarkupMatches($"

    Hello Developers. The base URL is: /

    "); @@ -19,7 +19,7 @@ public void ShouldUseCorrectBaseAddress() { var hostEnvironment = Services.GetRequiredService(); hostEnvironment.BaseAddress = "myBaseUrl/"; - var cut = RenderComponent(); + var cut = Render(); // Assert - inspect markup to verify that the BaseAddress is used correctly. cut.Find("p").MarkupMatches($"

    Hello World. The base URL is: myBaseUrl/

    "); diff --git a/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs index 3cc30aafb..3dfc0e8e6 100644 --- a/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs +++ b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs @@ -10,7 +10,7 @@ private sealed class ComponentDouble : ComponentDoubleBase>>((attrName, attrValue)); + var cut = Render>>((attrName, attrValue)); cut.Instance.Parameters[attrName].ShouldBe(attrValue); } diff --git a/tests/bunit.tests/TestDoubles/Components/StubTest.cs b/tests/bunit.tests/TestDoubles/Components/StubTest.cs index 0cc4acbec..3208fe99f 100644 --- a/tests/bunit.tests/TestDoubles/Components/StubTest.cs +++ b/tests/bunit.tests/TestDoubles/Components/StubTest.cs @@ -5,7 +5,7 @@ public class StubTest : TestContext [Fact(DisplayName = "Stub renders nothing without a replacement template")] public void Test001() { - var cut = RenderComponent>(); + var cut = Render>(); cut.Nodes.Length.ShouldBe(0); } @@ -14,7 +14,7 @@ public void Test001() [AutoData] public void Test002(string header, string attrValue) { - var cut = RenderComponent>( + var cut = Render>( (nameof(Simple1.Header), header), (nameof(Simple1.AttrValue), attrValue)); diff --git a/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs index 453dcf902..6b85552bc 100644 --- a/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs @@ -88,7 +88,7 @@ void Sut_LocationChanged(object? sender, LocationChangedEventArgs e) public void Test006() { var sut = CreateNavigationManager(); - var cut = RenderComponent(); + var cut = Render(); sut.NavigateTo("foo"); @@ -166,7 +166,7 @@ public void Test009() public void Test010() { var navigationManager = CreateNavigationManager(); - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -178,7 +178,7 @@ public void Test010() public void Test011() { var navigationManager = CreateNavigationManager(); - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); @@ -189,7 +189,7 @@ public void Test011() public void Test012() { var navigationManager = CreateNavigationManager(); - var cut = RenderComponent(); + var cut = Render(); cut.Find("button").Click(); diff --git a/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs b/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs index 306760a11..e25bfd14d 100644 --- a/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs +++ b/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs @@ -22,7 +22,7 @@ public void Test002() { this.AddBunitPersistentComponentState(); - var cut = RenderComponent(); + var cut = Render(); cut.Instance.State.ShouldNotBeNull(); } @@ -44,7 +44,7 @@ public void Test011(string key, string data) public void Test012() { var state = this.AddBunitPersistentComponentState(); - var cut = RenderComponent(); + var cut = Render(); state.TriggerOnPersisting(); diff --git a/tests/bunit.tests/TestServiceProviderTest.cs b/tests/bunit.tests/TestServiceProviderTest.cs index 83e6898ae..363fc1105 100644 --- a/tests/bunit.tests/TestServiceProviderTest.cs +++ b/tests/bunit.tests/TestServiceProviderTest.cs @@ -180,7 +180,7 @@ public void Test030() ctx.Services.AddFallbackServiceProvider(fallbackServiceProvider); // Act and assert - Should.NotThrow(() => ctx.RenderComponent()); + Should.NotThrow(() => ctx.Render()); } [Fact(DisplayName = "Can correctly resolve and dispose of scoped disposable service")] @@ -303,7 +303,7 @@ public void Test040() using var ctx = new TestContext(); ctx.Services.AddKeyedScoped("Key"); - var cut = ctx.RenderComponent(); + var cut = ctx.Render(); cut.Instance.Service.ShouldNotBeNull(); } @@ -316,7 +316,7 @@ public void Test041() fallbackCollection.AddKeyedScoped("Key"); ctx.Services.AddFallbackServiceProvider(fallbackCollection.BuildServiceProvider()); - var cut = ctx.RenderComponent(); + var cut = ctx.Render(); cut.Instance.Service.ShouldNotBeNull(); } @@ -326,7 +326,7 @@ public void Test042() { using var ctx = new TestContext(); - Should.Throw(() => ctx.RenderComponent()); + Should.Throw(() => ctx.Render()); } private sealed class DummyService { } From cc9f2cbc971127a66942a17dd7189e98e30a51f5 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 17:32:14 +0100 Subject: [PATCH 014/100] refactor: Remove Extensions methods for TestContext and moved them to Testcontext directly --- MIGRATION.md | 11 +++--- .../tests/xunit/InjectAuthServiceTest.cs | 4 +-- docs/samples/tests/xunit/UserInfoTest.cs | 8 ++--- docs/samples/tests/xunit/UserRightsTest.cs | 16 ++++----- docs/site/docs/test-doubles/auth.md | 18 +++++----- src/bunit/TestContext.cs | 2 +- ...ontext.cs => BunitAuthorizationContext.cs} | 23 ++++++------ .../BunitAuthorizationExtensions.cs | 23 +++++------- .../TestContextExtensions.cs | 21 +++++------ .../Authorization/AuthorizationTest.cs | 36 +++++++++---------- ...t.cs => BunitAuthorizationContextBunit.cs} | 14 ++++---- .../BunitSignOutSessionStateManagerTest.cs | 2 +- 12 files changed, 84 insertions(+), 94 deletions(-) rename src/bunit/TestDoubles/Authorization/{TestAuthorizationContext.cs => BunitAuthorizationContext.cs} (84%) rename tests/bunit.tests/TestDoubles/Authorization/{TestAuthorizationContextTest.cs => BunitAuthorizationContextBunit.cs} (88%) diff --git a/MIGRATION.md b/MIGRATION.md index d9726ca1c..0de860856 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -4,9 +4,9 @@ This document describes the changes that need to be made to migrate from bUnit 1 ## Removal of `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods The `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods have been removed from `RenderedComponent`. There is no one-to-one replacement for these methods, but the general idea is to select the HTML in question via `Find` and assert against that. -Alternatively, the `IRenderFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. +Alternatively, the `IRenderedFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. -## Removal of `IsNullOrEmpty` extension method on `IEnumerable` and `CreateLogger` on `IserviceProvider` +## Removal of `IsNullOrEmpty` extension method on `IEnumerable` and `CreateLogger` on `IServiceProvider` The `IsNullOrEmpty` extension method on `IEnumerable` has been removed, as well as the `CreateLogger` extension method on `IServiceProvider`. These extension methods are pretty common and conflict with other libraries. These methods can be recreated like this: ```csharp @@ -29,10 +29,11 @@ The `bunit.core` and `bunit.web` packages have been merged into a single `bunit` ## Removal of unneeded abstraction ### `IRenderedComponentBase` and `RenderedFragmentBase` -`IRenderedComponentBase` and `RenderedFragmentBase` have been removed. They were used to provide a common base class for `RenderedComponent` and `RenderedFragment`, but this is no longer needed (due to the merge of the project). If you used either of these interfaces, you should replace them with `RenderedComponent` and `RenderedFragment` respectively. +`IRenderedComponentBase`, `IRenderedComponent`, `IRenderedFragmentBase`, `IRenderedFragment` and `RenderedFragmentBase` have been removed. +If you used either of these types, you should replace them with `RenderedComponent` or `RenderedFragment` respectively. -### `WebTestRender` merged into `TestRender` -The `WebTestRender` class has been merged into the `TestRender` class. If you used `WebTestRender`, you should replace it with `TestRender`. +### `WebTestRender` merged into `BunitTestRender` +The `WebTestRender` class has been merged into the `TestRender` class. If you used `WebTestRender`, you should replace it with `BunitTestRender`. ## Renamed `Fake` to `Bunit` in many test doubles The `Fake` prefix has been replaced with `Bunit` in many test doubles. For example, `FakeNavigationManager` is now `BunitNavigationManager`. If you reference any of these types explicitly, you need to update your code. diff --git a/docs/samples/tests/xunit/InjectAuthServiceTest.cs b/docs/samples/tests/xunit/InjectAuthServiceTest.cs index a6b60335a..5b2ff5d7c 100644 --- a/docs/samples/tests/xunit/InjectAuthServiceTest.cs +++ b/docs/samples/tests/xunit/InjectAuthServiceTest.cs @@ -10,7 +10,7 @@ public class InjectAuthServiceTest : TestContext public void Test001() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUserName", AuthorizationState.Authorized); // act @@ -24,7 +24,7 @@ public void Test001() public void Test002() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); // act var cut = Render(); diff --git a/docs/samples/tests/xunit/UserInfoTest.cs b/docs/samples/tests/xunit/UserInfoTest.cs index 4274346cc..cca924096 100644 --- a/docs/samples/tests/xunit/UserInfoTest.cs +++ b/docs/samples/tests/xunit/UserInfoTest.cs @@ -9,7 +9,7 @@ public class UserInfoTest : TestContext public void Test001() { // Arrange - this.AddAuthorization(); + AddAuthorization(); // Act var cut = Render(); @@ -23,7 +23,7 @@ public void Test001() public void Test004() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorizing(); // Act @@ -38,7 +38,7 @@ public void Test004() public void Test002() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER", AuthorizationState.Unauthorized); // Act @@ -53,7 +53,7 @@ public void Test002() public void Test003() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); // Act diff --git a/docs/samples/tests/xunit/UserRightsTest.cs b/docs/samples/tests/xunit/UserRightsTest.cs index bb8076797..47fb3638e 100644 --- a/docs/samples/tests/xunit/UserRightsTest.cs +++ b/docs/samples/tests/xunit/UserRightsTest.cs @@ -11,7 +11,7 @@ public class UserRightsTest : TestContext public void Test001() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); // Act @@ -26,7 +26,7 @@ public void Test001() public void Test002() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetRoles("superuser"); @@ -44,7 +44,7 @@ public void Test002() public void Test003() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetRoles("admin", "superuser"); @@ -63,7 +63,7 @@ public void Test003() public void Test004() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetPolicies("content-editor"); @@ -81,7 +81,7 @@ public void Test004() public void Test0041() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetPolicies("content-editor", "approver"); @@ -99,7 +99,7 @@ public void Test0041() public void Test006() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetClaims( new Claim(ClaimTypes.Email, "test@example.com"), @@ -121,7 +121,7 @@ public void Test006() public void Test005() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetRoles("admin", "superuser"); authContext.SetPolicies("content-editor"); @@ -144,7 +144,7 @@ public void Test005() public void Test007() { // Arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TEST USER"); authContext.SetAuthenticationType("custom-auth-type"); diff --git a/docs/site/docs/test-doubles/auth.md b/docs/site/docs/test-doubles/auth.md index 3decf8909..85527296e 100644 --- a/docs/site/docs/test-doubles/auth.md +++ b/docs/site/docs/test-doubles/auth.md @@ -15,10 +15,10 @@ The test implementation of Blazor's authentication and authorization can be put - **Authenticated** and **authorized** - **Authenticated** and **authorized** with one or more **roles**, **claims**, and/or **policies** -bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContext)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. +bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.TestContext.AddAuthorization(Bunit.TestContext)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. > [!NOTE] -> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.TestDoubles.BunitAuthorizationExtensions.AddAuthorization(Bunit.TestContext)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `this.AddAuthorization()`. +> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.TestContext.AddAuthorization(Bunit.TestContext)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `AddAuthorization()`. The following sections show how to set each of these states in a test. @@ -46,7 +46,7 @@ To set the state to authenticating and authorizing, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=25&end=34&highlight=3)] -After calling `AddAuthorization()`, the returned is used to set the authenticating and authorizing state through the method. +After calling `AddAuthorization()`, the returned is used to set the authenticating and authorizing state through the method. ### Authenticated and unauthorized state @@ -54,7 +54,7 @@ To set the state to authenticated and unauthorized, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=40&end=49&highlight=3)] -After calling `AddAuthorization()`, the returned is used to set the authenticated and unauthorized state through the method. +After calling `AddAuthorization()`, the returned is used to set the authenticated and unauthorized state through the method. ### Authenticated and authorized state @@ -62,7 +62,7 @@ To set the state to authenticated and authorized, do the following: [!code-csharp[UserInfoTest.cs](../../../samples/tests/xunit/UserInfoTest.cs?start=55&end=64&highlight=3)] -After calling `AddAuthorization()`, the returned is used to set the authenticated and authorized state through the method. +After calling `AddAuthorization()`, the returned is used to set the authenticated and authorized state through the method. Note that the second parameter, `AuthorizationState`, is optional, and defaults to `AuthorizationState.Authorized` if not specified. @@ -80,7 +80,7 @@ To specify one or more roles for the authenticated and authorized user, do the f [!code-csharp[UserRightsTest.cs](../../../samples/tests/xunit/UserRightsTest.cs?start=28&end=40&highlight=4)] -The highlighted line shows how the method is used to specify a single role. To specify multiple roles, do the following: +The highlighted line shows how the method is used to specify a single role. To specify multiple roles, do the following: [!code-csharp[UserRightsTest.cs](../../../samples/tests/xunit/UserRightsTest.cs?start=46&end=59&highlight=4)] @@ -90,7 +90,7 @@ To specify one or more policies for the authenticated and authorized user, do th [!code-csharp[UserRightsTest.cs](../../../samples/tests/xunit/UserRightsTest.cs?start=65&end=78&highlight=5)] -The highlighted line shows how the method is used to specify one policy. To specify multiple policies, do the following: +The highlighted line shows how the method is used to specify one policy. To specify multiple policies, do the following: [!code-csharp[](../../../samples/tests/xunit/UserRightsTest.cs?start=91&end=91)] @@ -100,7 +100,7 @@ To specify one or more claims for the authenticated and authorized user, do the [!code-csharp[UserRightsTest.cs](../../../samples/tests/xunit/UserRightsTest.cs?start=101&end=117&highlight=4-7)] -The highlighted line shows how the method is used to pass two instances of the `Claim` type. +The highlighted line shows how the method is used to pass two instances of the `Claim` type. ### Example of passing both roles, claims, and policies @@ -116,4 +116,4 @@ To specify a authentication type for the authenticated and authorized user, do t [!code-csharp[UserRightsTest.cs](../../../samples/tests/xunit/UserRightsTest.cs?start=146&end=158&highlight=4)] -The highlighted line shows how the method is used to change the `Identity.AuthenticationType` of the user. +The highlighted line shows how the method is used to change the `Identity.AuthenticationType` of the user. diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 1de3d7876..4f2abf756 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -7,7 +7,7 @@ namespace Bunit; /// /// A test context is a factory that makes it possible to create components under tests. /// -public class TestContext : IDisposable +public partial class TestContext : IDisposable { private bool disposed; private BunitRenderer? bunitRenderer; diff --git a/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs similarity index 84% rename from src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs rename to src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs index 4594b8fd0..0667cf429 100644 --- a/src/bunit/TestDoubles/Authorization/TestAuthorizationContext.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs @@ -8,7 +8,7 @@ namespace Bunit.TestDoubles; /// Root authorization service that manages different authentication/authorization state /// in the system. /// -public class TestAuthorizationContext +public class BunitAuthorizationContext { private readonly BunitAuthorizationService authService = new(); private readonly BunitAuthorizationPolicyProvider policyProvider = new(); @@ -51,14 +51,15 @@ public class TestAuthorizationContext public string PolicySchemeName { get; set; } = "TestScheme"; /// - /// Registers authorization services with the specified service provider. + /// Creates a new instance of . /// - /// Service provider to use. - public void RegisterAuthorizationServices(IServiceCollection services) + internal BunitAuthorizationContext(TestServiceProvider services) { services.AddSingleton(authService); services.AddSingleton(policyProvider); services.AddSingleton(authProvider); + + authService.SetAuthorizationState(AuthorizationState.Unauthorized); } /// @@ -66,7 +67,7 @@ public void RegisterAuthorizationServices(IServiceCollection services) /// /// User name for the principal identity. /// Authorization state. - public TestAuthorizationContext SetAuthorized(string userName, AuthorizationState state = AuthorizationState.Authorized) + public BunitAuthorizationContext SetAuthorized(string userName, AuthorizationState state = AuthorizationState.Authorized) { IsAuthenticated = true; UserName = userName; @@ -83,7 +84,7 @@ public TestAuthorizationContext SetAuthorized(string userName, AuthorizationStat /// /// Puts the authorization services into the authorizing state. /// - public TestAuthorizationContext SetAuthorizing() + public BunitAuthorizationContext SetAuthorizing() { IsAuthenticated = false; Roles = Array.Empty(); @@ -99,7 +100,7 @@ public TestAuthorizationContext SetAuthorizing() /// /// Puts the authorization services into an unauthenticated and unauthorized state. /// - public TestAuthorizationContext SetNotAuthorized() + public BunitAuthorizationContext SetNotAuthorized() { IsAuthenticated = false; Roles = Array.Empty(); @@ -116,7 +117,7 @@ public TestAuthorizationContext SetNotAuthorized() /// Sets the user roles in this context.. /// /// Roles for the claims principal. - public TestAuthorizationContext SetRoles(params string[] roles) + public BunitAuthorizationContext SetRoles(params string[] roles) { Roles = roles; authService.SetRoles(Roles); @@ -129,7 +130,7 @@ public TestAuthorizationContext SetRoles(params string[] roles) /// Sets the authorization policies supported for the current user. /// /// Supported authorization policies. - public TestAuthorizationContext SetPolicies(params string[] policies) + public BunitAuthorizationContext SetPolicies(params string[] policies) { Policies = policies; policyProvider.SetPolicyScheme(PolicySchemeName); @@ -142,7 +143,7 @@ public TestAuthorizationContext SetPolicies(params string[] policies) /// Sets the claims on the current user/principal. /// /// Claims to set. - public TestAuthorizationContext SetClaims(params Claim[] claims) + public BunitAuthorizationContext SetClaims(params Claim[] claims) { Claims = claims; authProvider.TriggerAuthenticationStateChanged(UserName, Roles, Claims); @@ -154,7 +155,7 @@ public TestAuthorizationContext SetClaims(params Claim[] claims) /// Sets the Identity.AuthenticationType for the current user/principa;. /// /// The authentication type to set. - public TestAuthorizationContext SetAuthenticationType(string authenticationType) + public BunitAuthorizationContext SetAuthenticationType(string authenticationType) { this.authProvider.TriggerAuthenticationStateChanged(this.UserName, this.Roles, this.Claims, authenticationType); return this; diff --git a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs index dbd62c071..9d86fc4f0 100644 --- a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs @@ -1,31 +1,24 @@ +using Bunit.TestDoubles; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.WebAssembly.Authentication; -namespace Bunit.TestDoubles; +namespace Bunit; -/// -/// Helper methods for registering the Authentication/Authorization services with -/// a . -/// -public static class BunitAuthorizationExtensions +public partial class TestContext { /// /// Adds the appropriate Blazor authentication and authorization services to the to enable /// an authenticated user, as well as adding the component to the /// test contexts render tree. /// - public static TestAuthorizationContext AddAuthorization(this TestContext context) + public BunitAuthorizationContext AddAuthorization() { - ArgumentNullException.ThrowIfNull(context); - - context.RenderTree.TryAdd(); - context.Services.AddSingleton(); + RenderTree.TryAdd(); + Services.AddSingleton(); #pragma warning disable CS0618 - context.Services.AddSingleton(s => s.GetRequiredService()); + Services.AddSingleton(s => s.GetRequiredService()); #pragma warning restore CS0618 - var authCtx = new TestAuthorizationContext(); - authCtx.SetNotAuthorized(); - authCtx.RegisterAuthorizationServices(context.Services); + var authCtx = new BunitAuthorizationContext(Services); return authCtx; } } diff --git a/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs b/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs index f0d3b655c..b545938b9 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs @@ -1,23 +1,18 @@ +using Bunit.TestDoubles; using Microsoft.AspNetCore.Components.Infrastructure; -namespace Bunit.TestDoubles; +namespace Bunit; -/// -/// Extensions related to . -/// -public static class TestContextExtensions +public partial class TestContext { /// - /// Adds and returns a to the services of the . + /// Adds and returns a to the services of this . /// - /// The test context to add the to. /// The added . - public static BunitPersistentComponentState AddBunitPersistentComponentState(this TestContext testContext) + public BunitPersistentComponentState AddBunitPersistentComponentState() { - ArgumentNullException.ThrowIfNull(testContext); - - testContext.Services.AddSingleton(); - testContext.Services.AddSingleton(s => s.GetRequiredService().State); - return new BunitPersistentComponentState(testContext.Services); + Services.AddSingleton(); + Services.AddSingleton(s => s.GetRequiredService().State); + return new BunitPersistentComponentState(Services); } } diff --git a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs index f7f66e4c3..e64ab77c3 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs @@ -14,7 +14,7 @@ public AuthorizationTest(ITestOutputHelper outputHelper) public void Test001() { // Arrange - this.AddAuthorization(); + AddAuthorization(); // Act var cut = Render(); @@ -27,7 +27,7 @@ public void Test001() public void Test002() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser", AuthorizationState.Authorized); // act @@ -41,7 +41,7 @@ public void Test002() public void Test003() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser", AuthorizationState.Unauthorized); // act @@ -56,7 +56,7 @@ public void Test003() public async Task Test004() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); // start off unauthenticated. var cut = Render(); @@ -76,7 +76,7 @@ public async Task Test004() public void Test004_Sync() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); // start off unauthenticated. var cut = Render(); @@ -95,7 +95,7 @@ public void Test004_Sync() public void Test005() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser005", AuthorizationState.Authorized); // start off unauthenticated. @@ -126,7 +126,7 @@ public void Test006() public void Test007() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser").SetPolicies("ContentViewer"); // act @@ -140,7 +140,7 @@ public void Test007() public void Test008() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser"); // act @@ -154,7 +154,7 @@ public void Test008() public void Test0081() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser").SetPolicies("OtherPolicy"); // act @@ -168,7 +168,7 @@ public void Test0081() public void Test009() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser").SetRoles("Admin"); // act @@ -182,7 +182,7 @@ public void Test009() public void Test010() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser"); // act @@ -196,7 +196,7 @@ public void Test010() public void Test011() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser").SetRoles("NotAdmin"); // act @@ -210,7 +210,7 @@ public void Test011() public void Test012() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorizing(); // act @@ -225,7 +225,7 @@ public void Test013() { // arrange var userId = new Guid("{5d5fa9c1-abf9-4ed6-8fb0-3365382b629c}"); - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); var emailClaim = new Claim(ClaimTypes.Email, "user@test.com"); var uuidClaim = new Claim(ClaimTypes.Sid, userId.ToString()); authContext.SetAuthorized("TestUser").SetClaims(uuidClaim, emailClaim); @@ -244,7 +244,7 @@ public void Test013() public void Test014() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser"); // act @@ -259,7 +259,7 @@ public void Test014() public void Test020() { var role = "myTestRole"; - var authCtx = this.AddAuthorization(); + var authCtx = AddAuthorization(); authCtx.SetAuthorized("FooBar"); authCtx.SetRoles(role); @@ -272,7 +272,7 @@ public void Test020() public void Test021() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser"); authContext.SetAuthenticationType("custom-auth-type"); @@ -287,7 +287,7 @@ public void Test021() public void Test022() { // arrange - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("TestUser"); // act diff --git a/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs similarity index 88% rename from tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs index 63917997d..25b4d8e8e 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/TestAuthorizationContextTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs @@ -1,12 +1,12 @@ namespace Bunit.TestDoubles.Authorization; -public class TestAuthorizationContextTest : TestContext +public class BunitAuthorizationContextBunit : TestContext { [Fact(DisplayName = "Register Authorization services with unauthenticated user.")] public void Test003() { // act - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); // assert Assert.False(authContext.IsAuthenticated); @@ -19,7 +19,7 @@ public void Test003() public void Test0031() { // act - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorizing(); // assert @@ -33,7 +33,7 @@ public void Test0031() public void Test002() { // act - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("DarthPedro", AuthorizationState.Unauthorized); // assert @@ -47,7 +47,7 @@ public void Test002() public void Test0010() { // act - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("DarthPedro"); // assert @@ -61,7 +61,7 @@ public void Test0010() public void Test001() { // act - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("DarthPedro"); authContext.SetRoles("some-role"); @@ -76,7 +76,7 @@ public void Test001() public void Test0011() { // act - var authContext = this.AddAuthorization(); + var authContext = AddAuthorization(); authContext.SetAuthorized("DarthPedro"); authContext.SetPolicies("TestPolicy", "Other"); diff --git a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs index 7c3c1a038..a44403380 100644 --- a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs @@ -5,7 +5,7 @@ public class BunitSignOutSessionStateManagerTest : TestContext [Theory, AutoData] public void ShouldSignOut(string randomUserName) { - this.AddAuthorization().SetAuthorized(randomUserName); + AddAuthorization().SetAuthorized(randomUserName); var cut = Render(); cut.Find("button").Click(); From 846b0c5bfe31a2224a7e1e85277b686353a506f8 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 21:08:35 +0100 Subject: [PATCH 015/100] refactor: Check for duplicates in one pass-through --- src/bunit/ComponentParameterCollection.cs | 67 +++++++---------------- 1 file changed, 21 insertions(+), 46 deletions(-) diff --git a/src/bunit/ComponentParameterCollection.cs b/src/bunit/ComponentParameterCollection.cs index f8052c5c0..86fb0b81e 100644 --- a/src/bunit/ComponentParameterCollection.cs +++ b/src/bunit/ComponentParameterCollection.cs @@ -9,15 +9,15 @@ public class ComponentParameterCollection : ICollection, IRe { private static readonly MethodInfo CreateTemplateWrapperMethod = GetCreateTemplateWrapperMethod(); private static readonly Type CascadingValueType = typeof(CascadingValue<>); - private List? parameters; + private readonly List parameters = new(); /// /// Gets the number of in the collection. /// - public int Count => parameters?.Count ?? 0; + public int Count => parameters.Count; /// - public bool IsReadOnly { get; } + public bool IsReadOnly => false; /// /// Adds a to the collection. @@ -28,9 +28,6 @@ public void Add(ComponentParameter item) if (item.Name is null && item.Value is null) throw new ArgumentException("A component parameter without a name and value is not valid.", nameof(item)); - if (parameters is null) - parameters = new List(); - parameters.Add(item); } @@ -53,16 +50,16 @@ public void Add(IEnumerable parameters) /// /// Parameter to check with. /// True if is in the collection, false otherwise. - public bool Contains(ComponentParameter item) => parameters?.Contains(item) ?? false; + public bool Contains(ComponentParameter item) => parameters.Contains(item); /// - public void Clear() => parameters?.Clear(); + public void Clear() => parameters.Clear(); /// - public void CopyTo(ComponentParameter[] array, int arrayIndex) => parameters?.CopyTo(array, arrayIndex); + public void CopyTo(ComponentParameter[] array, int arrayIndex) => parameters.CopyTo(array, arrayIndex); /// - public bool Remove(ComponentParameter item) => parameters?.Remove(item) ?? false; + public bool Remove(ComponentParameter item) => parameters.Remove(item); /// /// Creates a that will render a @@ -108,9 +105,6 @@ void AddComponent(RenderTreeBuilder builder) void AddAttributes(RenderTreeBuilder builder) { - if (parameters is null) - return; - var attrCount = 100; foreach (var pgroup in parameters.Where(x => !x.IsCascadingValue).GroupBy(x => x.Name, StringComparer.Ordinal)) @@ -148,7 +142,7 @@ void AddAttributes(RenderTreeBuilder builder) var groupType = groupObject?.GetType(); - if (groupType != null && groupType.IsGenericType && groupType.GetGenericTypeDefinition() == typeof(RenderFragment<>)) + if (groupType is { IsGenericType: true } && groupType.GetGenericTypeDefinition() == typeof(RenderFragment<>)) { builder.AddAttribute( attrCount++, @@ -164,32 +158,22 @@ void AddAttributes(RenderTreeBuilder builder) Queue<(ComponentParameter Parameter, Type Type)> GetCascadingValues() { - var cascadingValues = parameters?.Where(x => x.IsCascadingValue) + var cascadingValues = parameters + .Where(x => x.IsCascadingValue) .Select(x => (Parameter: x, Type: GetCascadingValueType(x))) - .ToArray() ?? Array.Empty<(ComponentParameter Parameter, Type Type)>(); + .ToArray(); - // Detect duplicated unnamed values - for (var i = 0; i < cascadingValues.Length; i++) + var duplicate = cascadingValues + .GroupBy(x => new { x.Type, x.Parameter.Name }) + .FirstOrDefault(g => g.Count() > 1); + + if (duplicate is not null) { - for (var j = i + 1; j < cascadingValues.Length; j++) - { - if (cascadingValues[i].Type == cascadingValues[j].Type) - { - var iName = cascadingValues[i].Parameter.Name; - if (iName is null) - { - var cascadingValueType = cascadingValues[i].Type.GetGenericArguments()[0]; - throw new ArgumentException($"Two or more unnamed cascading values with the type '{cascadingValueType.Name}' was added. " + - $"Only add one unnamed cascading value of the same type."); - } + var name = duplicate.Key.Name; + var type = duplicate.First().Type.GetGenericArguments()[0]; - if (iName.Equals(cascadingValues[j].Parameter.Name, StringComparison.Ordinal)) - { - throw new ArgumentException($"Two or more named cascading values with the name '{iName}' and the same type was added. " + - $"Only add one named cascading value with the same name and type."); - } - } - } + throw new ArgumentException($"Two or more unnamed cascading values with the type '{name ?? type.Name}' was added. " + + $"Only add one unnamed cascading value of the same type."); } return new Queue<(ComponentParameter Parameter, Type Type)>(cascadingValues); @@ -197,16 +181,7 @@ void AddAttributes(RenderTreeBuilder builder) } /// - public IEnumerator GetEnumerator() - { - if (parameters is not null) - { - for (var i = 0; i < parameters.Count; i++) - { - yield return parameters[i]; - } - } - } + public IEnumerator GetEnumerator() => parameters.GetEnumerator(); /// System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); From be813dace3fb9c5ef4654f8913742338ceca45e6 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sun, 3 Mar 2024 22:00:12 +0100 Subject: [PATCH 016/100] refactor: Remove RenderedComponentActivator --- .../MarkupMatchesAssertExtensions.cs | 1 - .../ComponentParameterCollectionBuilder.cs | 2 - .../Extensions/BunitRendererExtensions.cs | 4 +- .../RenderedComponentRenderExtensions.cs | 1 - .../TestServiceProviderExtensions.cs | 1 - src/bunit/Rendering/BunitRenderer.cs | 31 ++-- .../Rendering/IRenderedComponentActivator.cs | 25 ---- .../Rendering/RenderedComponentActivator.cs | 31 ---- src/bunit/TestContext.cs | 5 +- .../Asserting/MarkupMatchesTests.razor | 1 - ...RendererBunit.cs => BunitRendererTests.cs} | 135 +++++------------- 11 files changed, 57 insertions(+), 180 deletions(-) delete mode 100644 src/bunit/Rendering/IRenderedComponentActivator.cs delete mode 100644 src/bunit/Rendering/RenderedComponentActivator.cs rename tests/bunit.tests/Rendering/{BunitRendererBunit.cs => BunitRendererTests.cs} (80%) diff --git a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs index 4bb3fc51b..e4b4cee8e 100644 --- a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs +++ b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs @@ -275,7 +275,6 @@ public static void MarkupMatches(this RenderedFragment actual, RenderFragment ex // TODO: This will be obsolete with: https://github.com/bUnit-dev/bUnit/issues/1018 // As the renderer would be transient we don't have to new up an instance using var renderer = new BunitRenderer( - actual.Services.GetRequiredService(), actual.Services.GetRequiredService(), actual.Services.GetRequiredService()); var renderedFragment = renderer.RenderFragment(expected); diff --git a/src/bunit/ComponentParameterCollectionBuilder.cs b/src/bunit/ComponentParameterCollectionBuilder.cs index 9d54fd638..c088c2717 100644 --- a/src/bunit/ComponentParameterCollectionBuilder.cs +++ b/src/bunit/ComponentParameterCollectionBuilder.cs @@ -1,8 +1,6 @@ using System.Linq.Expressions; using System.Reflection; -using System.Runtime.CompilerServices; using Bunit.Extensions; -using Bunit.Rendering; namespace Bunit; diff --git a/src/bunit/Extensions/BunitRendererExtensions.cs b/src/bunit/Extensions/BunitRendererExtensions.cs index 80d2de89b..2ef8a7473 100644 --- a/src/bunit/Extensions/BunitRendererExtensions.cs +++ b/src/bunit/Extensions/BunitRendererExtensions.cs @@ -24,7 +24,7 @@ public static RenderedComponent Render(this BunitRendere if (resultBase is RenderedComponent result) return result; - throw new InvalidOperationException($"The renderer did not produce the expected type. Is the test renderer using the expected {nameof(IRenderedComponentActivator)}?"); + throw new InvalidOperationException($"The renderer did not produce the expected type."); } /// @@ -45,6 +45,6 @@ public static RenderedComponent Render(this BunitRendere if (resultBase is RenderedComponent result) return result; - throw new InvalidOperationException($"The renderer did not produce the expected type. Is the test renderer using the expected {nameof(IRenderedComponentActivator)}?"); + throw new InvalidOperationException($"The renderer did not produce the expected type."); } } diff --git a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs index f35eba495..bc74ee5d1 100644 --- a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs @@ -1,4 +1,3 @@ -using Bunit.Rendering; using System.Runtime.ExceptionServices; namespace Bunit; diff --git a/src/bunit/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/TestServiceProviderExtensions.cs index ce42faeff..d40a08350 100644 --- a/src/bunit/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit/Extensions/TestServiceProviderExtensions.cs @@ -50,7 +50,6 @@ public static IServiceCollection AddDefaultTestContextServices(this IServiceColl services.AddSingleton(testContext); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); services.AddMemoryCache(); diff --git a/src/bunit/Rendering/BunitRenderer.cs b/src/bunit/Rendering/BunitRenderer.cs index ec850d521..661f4bb68 100644 --- a/src/bunit/Rendering/BunitRenderer.cs +++ b/src/bunit/Rendering/BunitRenderer.cs @@ -10,6 +10,8 @@ namespace Bunit.Rendering; /// public sealed class BunitRenderer : Renderer { + private readonly TestServiceProvider services; + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")] private static extern ref bool GetIsBatchInProgressField(Renderer renderer); @@ -20,7 +22,6 @@ public sealed class BunitRenderer : Renderer private readonly Dictionary renderedComponents = new(); private readonly List rootComponents = new(); private readonly ILogger logger; - private readonly IRenderedComponentActivator activator; private bool disposed; private TaskCompletionSource unhandledExceptionTsc = new(TaskCreationOptions.RunContinuationsAsynchronously); private Exception? capturedUnhandledException; @@ -56,22 +57,22 @@ private bool IsBatchInProgress /// /// Initializes a new instance of the class. /// - public BunitRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory) + public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory) : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), null)) { + this.services = services; logger = loggerFactory.CreateLogger(); - activator = renderedComponentActivator; ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } /// /// Initializes a new instance of the class. /// - public BunitRenderer(IRenderedComponentActivator renderedComponentActivator, TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) + public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), componentActivator)) { + this.services = services; logger = loggerFactory.CreateLogger(); - activator = renderedComponentActivator; ElementReferenceContext = new WebElementReferenceContext(services.GetRequiredService()); } @@ -81,7 +82,7 @@ public BunitRenderer(IRenderedComponentActivator renderedComponentActivator, Tes /// The to render. /// A that provides access to the rendered . public RenderedFragment RenderFragment(RenderFragment renderFragment) - => Render(renderFragment, id => activator.CreateRenderedFragment(id)); + => Render(renderFragment); /// /// Renders a with the passed to it. @@ -95,7 +96,7 @@ public RenderedComponent Render(ComponentParameterCollec ArgumentNullException.ThrowIfNull(parameters); var renderFragment = parameters.ToRenderFragment(); - return Render(renderFragment, id => activator.CreateRenderedComponent(id)); + return Render(renderFragment).FindComponent(); } /// @@ -226,7 +227,6 @@ protected override IComponent ResolveComponentForRenderMode(Type componentType, return componentActivator.CreateInstance(componentType); } - /// internal Task SetDirectParametersAsync(RenderedFragment renderedComponent, ParameterView parameters) { ObjectDisposedException.ThrowIf(disposed, this); @@ -434,8 +434,7 @@ protected override void Dispose(bool disposing) } } - private TResult Render(RenderFragment renderFragment, Func activator) - where TResult : RenderedFragment + private RenderedFragment Render(RenderFragment renderFragment) { ObjectDisposedException.ThrowIf(disposed, this); @@ -445,14 +444,14 @@ private TResult Render(RenderFragment renderFragment, Func GetOrCreateRenderedComponent(R } LoadRenderTreeFrames(componentId, framesCollection); - var result = activator.CreateRenderedComponent(componentId, component, framesCollection); + var result = new RenderedComponent(componentId, component, framesCollection, services); renderedComponents.Add(result.ComponentId, result); return result; @@ -558,13 +557,13 @@ private void LoadRenderTreeFrames(int componentId, RenderTreeFrameDictionary fra /// private ArrayRange GetOrLoadRenderTreeFrame(RenderTreeFrameDictionary framesCollection, int componentId) { - if (!framesCollection.Contains(componentId)) + if (!framesCollection.TryGetValue(componentId, out var frames)) { - var frames = GetCurrentRenderTreeFrames(componentId); + frames = GetCurrentRenderTreeFrames(componentId); framesCollection.Add(componentId, frames); } - return framesCollection[componentId]; + return frames; } /// diff --git a/src/bunit/Rendering/IRenderedComponentActivator.cs b/src/bunit/Rendering/IRenderedComponentActivator.cs deleted file mode 100644 index dceb1ff32..000000000 --- a/src/bunit/Rendering/IRenderedComponentActivator.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Bunit.Rendering; - -/// -/// Represents an activator for and types. -/// -public interface IRenderedComponentActivator -{ - /// - /// Creates an with the specified . - /// - RenderedFragment CreateRenderedFragment(int componentId); - - /// - /// Creates an with the specified . - /// - RenderedComponent CreateRenderedComponent(int componentId) - where TComponent : IComponent; - - /// - /// Creates an with the specified , - /// , and . - /// - RenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) - where TComponent : IComponent; -} diff --git a/src/bunit/Rendering/RenderedComponentActivator.cs b/src/bunit/Rendering/RenderedComponentActivator.cs deleted file mode 100644 index 9b30f1418..000000000 --- a/src/bunit/Rendering/RenderedComponentActivator.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace Bunit.Rendering; - -/// -/// Represents a rendered component activator for bUnit.web. -/// -public sealed class RenderedComponentActivator : IRenderedComponentActivator -{ - private readonly IServiceProvider services; - - /// - /// Initializes a new instance of the class. - /// - public RenderedComponentActivator(IServiceProvider services) - { - this.services = services; - } - - /// - public RenderedFragment CreateRenderedFragment(int componentId) - => new RenderedFragment(componentId, services); - - /// - public RenderedComponent CreateRenderedComponent(int componentId) - where TComponent : IComponent - => new RenderedComponent(componentId, services); - - /// - public RenderedComponent CreateRenderedComponent(int componentId, TComponent component, RenderTreeFrameDictionary componentFrames) - where TComponent : IComponent - => new RenderedComponent(componentId, component, componentFrames, services); -} diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 4f2abf756..06e5dfe9f 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -177,12 +177,11 @@ protected virtual void BuildRenderTree(RenderTreeBuilder builder) { } private BunitRenderer CreateRenderer() { - var renderedComponentActivator = Services.GetRequiredService(); var logger = Services.GetRequiredService(); var componentActivator = Services.GetService(); return componentActivator is null - ? new BunitRenderer(renderedComponentActivator, Services, logger) - : new BunitRenderer(renderedComponentActivator, Services, logger, componentActivator); + ? new BunitRenderer(Services, logger) + : new BunitRenderer(Services, logger, componentActivator); } } diff --git a/tests/bunit.tests/Asserting/MarkupMatchesTests.razor b/tests/bunit.tests/Asserting/MarkupMatchesTests.razor index 5c22485fc..626e77807 100644 --- a/tests/bunit.tests/Asserting/MarkupMatchesTests.razor +++ b/tests/bunit.tests/Asserting/MarkupMatchesTests.razor @@ -1,4 +1,3 @@ -@using Bunit.TestAssets.SampleComponents @inherits TestContext @code { diff --git a/tests/bunit.tests/Rendering/BunitRendererBunit.cs b/tests/bunit.tests/Rendering/BunitRendererTests.cs similarity index 80% rename from tests/bunit.tests/Rendering/BunitRendererBunit.cs rename to tests/bunit.tests/Rendering/BunitRendererTests.cs index 37c204bcf..cb6c4cb7d 100644 --- a/tests/bunit.tests/Rendering/BunitRendererBunit.cs +++ b/tests/bunit.tests/Rendering/BunitRendererTests.cs @@ -1,34 +1,30 @@ using Bunit.Extensions; using Bunit.TestAssets.RenderModes; -using Microsoft.Extensions.Logging.Abstractions; using static Bunit.ComponentParameterFactory; namespace Bunit.Rendering; -public partial class BunitRendererBunit : TestContext +public class BunitRendererTests : TestContext { - public BunitRendererBunit(ITestOutputHelper outputHelper) + public BunitRendererTests(ITestOutputHelper outputHelper) { - TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); + DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(outputHelper); } [Fact(DisplayName = "RenderFragment re-throws exception from component")] public void Test004() { - using var sut = CreateRenderer(); RenderFragment throwingFragment = b => { b.OpenComponent(0); b.CloseComponent(); }; - Should.Throw(() => sut.RenderFragment(throwingFragment)) + Should.Throw(() => Renderer.RenderFragment(throwingFragment)) .Message.ShouldBe(ThrowsDuringSetParams.EXCEPTION.Message); } [Fact(DisplayName = "Render re-throws exception from component")] public void Test003() { - using var sut = CreateRenderer(); - - Should.Throw(() => sut.Render()) + Should.Throw(() => Renderer.Render()) .Message.ShouldBe(ThrowsDuringSetParams.EXCEPTION.Message); } @@ -36,9 +32,8 @@ public void Test003() public void Test001() { const string MARKUP = "

    hello world

    "; - using var sut = CreateRenderer(); - var cut = sut.RenderFragment(builder => builder.AddMarkupContent(0, MARKUP)); + var cut = Renderer.RenderFragment(builder => builder.AddMarkupContent(0, MARKUP)); cut.RenderCount.ShouldBe(1); cut.Markup.ShouldBe(MARKUP); @@ -47,9 +42,7 @@ public void Test001() [Fact(DisplayName = "Can render component without children and no parameters")] public void Test002() { - using var sut = CreateRenderer(); - - var cut = sut.Render(); + var cut = Renderer.Render(); cut.RenderCount.ShouldBe(1); cut.Markup.ShouldBe(NoChildNoParams.MARKUP); @@ -60,9 +53,8 @@ public void Test002() public void Test005() { const string VALUE = "FOO BAR"; - using var sut = CreateRenderer(); - var cut = sut.Render((nameof(HasParams.Value), VALUE)); + var cut = Renderer.Render((nameof(HasParams.Value), VALUE)); cut.Instance.Value.ShouldBe(VALUE); } @@ -73,9 +65,7 @@ public void Test006() const string PARENT_VALUE = "PARENT"; const string CHILD_VALUE = "CHILD"; - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( (nameof(HasParams.Value), PARENT_VALUE), ChildContent((nameof(HasParams.Value), CHILD_VALUE))); @@ -86,9 +76,7 @@ public void Test006() [Fact(DisplayName = "Rendered component gets RenderCount updated on re-render")] public async Task Test010() { - using var sut = CreateRenderer(); - - var cut = sut.Render(); + var cut = Renderer.Render(); cut.RenderCount.ShouldBe(1); @@ -102,8 +90,7 @@ public async Task Test011() { // arrange const string EXPECTED = "NOW VALUE"; - using var sut = CreateRenderer(); - var cut = sut.Render(); + var cut = Renderer.Render(); cut.RenderCount.ShouldBe(1); @@ -122,14 +109,12 @@ public void Test020() const string PARENT_VALUE = "PARENT"; const string CHILD_VALUE = "CHILD"; - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( (nameof(HasParams.Value), PARENT_VALUE), ChildContent((nameof(HasParams.Value), CHILD_VALUE))); // act - var childCut = sut.FindComponent(cut); + var childCut = Renderer.FindComponent(cut); // assert childCut.Markup.ShouldBe(CHILD_VALUE); @@ -139,30 +124,25 @@ public void Test020() [Fact(DisplayName = "FindComponent throws if parentComponent parameter is null")] public void Test021() { - using var sut = CreateRenderer(); - - Should.Throw(() => sut.FindComponent(null!)); + Should.Throw(() => Renderer.FindComponent(null!)); } [Fact(DisplayName = "FindComponent throws if component is not found")] public void Test022() { - using var sut = CreateRenderer(); - var cut = sut.Render(); + var cut = Renderer.Render(); - Should.Throw(() => sut.FindComponent(cut)); + Should.Throw(() => Renderer.FindComponent(cut)); } [Fact(DisplayName = "FindComponent returns same rendered component when called multiple times")] public void Test023() { - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( ChildContent()); - var child1 = sut.FindComponent(cut); - var child2 = sut.FindComponent(cut); + var child1 = Renderer.FindComponent(cut); + var child2 = Renderer.FindComponent(cut); child1.ShouldBe(child2); } @@ -175,9 +155,7 @@ public void Test030() const string PARENT_VALUE = nameof(PARENT_VALUE); const string CHILD_VALUE = nameof(CHILD_VALUE); - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( (nameof(HasParams.Value), GRAND_PARENT_VALUE), ChildContent( (nameof(HasParams.Value), PARENT_VALUE), @@ -185,7 +163,7 @@ public void Test030() (nameof(HasParams.Value), CHILD_VALUE)))); // act - var childCuts = sut.FindComponents(cut) + var childCuts = Renderer.FindComponents(cut) .OfType>() .ToList(); @@ -200,23 +178,20 @@ public void Test030() [Fact(DisplayName = "FindComponents throws if parentComponent parameter is null")] public void Test031() { - using var sut = CreateRenderer(); - - Should.Throw(() => sut.FindComponents(null!)); + Should.Throw(() => Renderer.FindComponents(null!)); } [Fact(DisplayName = "FindComponents returns same rendered components when called multiple times")] public void Test032() { // arrange - using var sut = CreateRenderer(); - var cut = sut.Render( + var cut = Renderer.Render( ChildContent( ChildContent())); // act - var childCuts1 = sut.FindComponents(cut); - var childCuts2 = sut.FindComponents(cut); + var childCuts1 = Renderer.FindComponents(cut); + var childCuts2 = Renderer.FindComponents(cut); // assert childCuts1.ShouldBe(childCuts2); @@ -225,13 +200,11 @@ public void Test032() [Fact(DisplayName = "Retrieved rendered child component with FindComponent gets updated on re-render")] public async Task Test040() { - using var sut = CreateRenderer(); - - var parent = sut.Render( + var parent = Renderer.Render( ChildContent()); // act - var cut = sut.FindComponent(parent); + var cut = Renderer.FindComponent(parent); cut.RenderCount.ShouldBe(1); @@ -244,13 +217,11 @@ public async Task Test040() [Fact(DisplayName = "Retrieved rendered child component with FindComponents gets updated on re-render")] public async Task Test041() { - using var sut = CreateRenderer(); - - var parent = sut.Render( + var parent = Renderer.Render( ChildContent()); // act - var cut = sut.FindComponents(parent).Single(); + var cut = Renderer.FindComponents(parent).Single(); cut.RenderCount.ShouldBe(1); @@ -264,11 +235,9 @@ public async Task Test041() public async Task Test050() { // arrange - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( ChildContent()); - var child = sut.FindComponent(cut); + var child = Renderer.FindComponent(cut); // act await child.Instance.TriggerWithValue("X"); @@ -282,11 +251,9 @@ public async Task Test050() public async Task Test060() { // arrange - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( ChildContent()); - var child = sut.FindComponent(cut); + var child = Renderer.FindComponent(cut); // act await cut.Instance.DisposeChild(); @@ -300,13 +267,11 @@ public async Task Test060() public async Task Test061() { // arrange - using var sut = CreateRenderer(); - - var cut = sut.Render( + var cut = Renderer.Render( ChildContent( ChildContent())); - var child = sut.FindComponent(cut); - var childChild = sut.FindComponent(cut); + var child = Renderer.FindComponent(cut); + var childChild = Renderer.FindComponent(cut); // act await child.Instance.DisposeChild(); @@ -319,10 +284,9 @@ public async Task Test061() [Fact(DisplayName = "When test renderer is disposed, so is all rendered components")] public void Test070() { - var sut = CreateRenderer(); - var cut = sut.Render(); + var cut = Renderer.Render(); - sut.Dispose(); + Renderer.Dispose(); cut.IsDisposed.ShouldBeTrue(); } @@ -487,29 +451,6 @@ public void Test211() cut.Find("h1").TextContent.ShouldBe($"Hello world {RenderMode.InteractiveWebAssembly}"); } - [Fact(DisplayName = "given a IComponentActivator, " + - "when passed to constructor," + - "then it used to create components")] - public void Test1000() - { - var activatorMock = Substitute.For(); - activatorMock.CreateInstance(typeof(Wrapper)).Returns(new Wrapper()); - using var renderer = new BunitRenderer( - Services.GetService(), - Services, - NullLoggerFactory.Instance, - activatorMock); - - renderer.Render(new ComponentParameterCollection()); - - activatorMock.Received(1).CreateInstance(typeof(Wrapper)); - } - - private BunitRenderer CreateRenderer() => new BunitRenderer( - Services.GetRequiredService(), - Services, - NullLoggerFactory.Instance); - internal sealed class LifeCycleMethodInvokeCounter : ComponentBase { public int InitilizedCount { get; private set; } From bb2a8999cb18ce678ee4f20e63e65eca17eea306 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Mon, 4 Mar 2024 20:50:31 +0100 Subject: [PATCH 017/100] refactor: Removed ComponentParameter and dependent types from public surface --- MIGRATION.md | 3 + .../tests/xunit/AllKindsOfParamsTest.cs | 342 ------------------ .../tests/xunit/NestedComponentTest.cs | 1 - docs/samples/tests/xunit/ReRenderTest.cs | 1 - docs/samples/tests/xunit/SemanticHtmlTest.cs | 1 - .../tests/xunit/VerifyMarkupExamples.cs | 1 - .../tests/xunit/WeatherForecastsTest.cs | 1 - docs/site/docs/interaction/trigger-renders.md | 10 +- .../inject-services-into-components.md | 2 +- .../passing-parameters-to-components.md | 2 +- .../verification/semantic-html-comparison.md | 2 +- docs/site/docs/verification/verify-markup.md | 6 +- src/bunit/ComponentParameter.cs | 21 +- src/bunit/ComponentParameterCollection.cs | 2 +- .../ComponentParameterCollectionBuilder.cs | 2 +- src/bunit/ComponentParameterFactory.cs | 242 ------------- .../Extensions/BunitRendererExtensions.cs | 30 +- .../RenderedComponentRenderExtensions.cs | 29 +- src/bunit/Rendering/BunitRenderer.cs | 15 - src/bunit/TestContext.cs | 15 - src/bunit/TestContextWrapper.cs | 12 +- .../CompareToDiffingExtensionsTest.cs | 32 +- .../ComponentParameterFactoryTest.cs | 277 -------------- .../EventDispatchExtensionsTest.cs | 4 +- .../TriggerEventSpy.cs | 15 +- .../Rendering/BunitRendererTests.cs | 59 ++- .../Rendering/ComponentParameterTest.cs | 47 --- .../Rendering/RenderedComponentTest.cs | 2 +- .../Rendering/RenderedFragmentTest.cs | 2 +- tests/bunit.tests/ShouldlyExtensions.cs | 2 +- tests/bunit.tests/TestContextTest.cs | 2 +- .../Components/ComponentDoubleBaseTest.cs | 3 +- .../TestDoubles/Components/StubTest.cs | 6 +- 33 files changed, 80 insertions(+), 1111 deletions(-) delete mode 100644 docs/samples/tests/xunit/AllKindsOfParamsTest.cs delete mode 100644 src/bunit/ComponentParameterFactory.cs delete mode 100644 tests/bunit.tests/ComponentParameterFactoryTest.cs diff --git a/MIGRATION.md b/MIGRATION.md index 0de860856..4fbde291a 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -46,3 +46,6 @@ The `TestContext` and `TestContextBase` classes have been merged into a single ` ## Renamed all `RenderComponent` and `SetParametersAndRender` to `Render` To make the API more consistent, `RenderComponent` and `SetParametersAndRender` methods have been renamed to `Render`. + +## Removal of `ComponentParameter` and method using them +Using `ComponentParameter` and factory methods to create them is not recommend in V1 and have now been removed in V2. Instead, use the strongly typed builder pattern that enables you to pass parameters to components you render. diff --git a/docs/samples/tests/xunit/AllKindsOfParamsTest.cs b/docs/samples/tests/xunit/AllKindsOfParamsTest.cs deleted file mode 100644 index 18c4fec4d..000000000 --- a/docs/samples/tests/xunit/AllKindsOfParamsTest.cs +++ /dev/null @@ -1,342 +0,0 @@ -using Xunit; -using Bunit; -using System.Collections.Generic; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Web; -using Bunit.Rendering; -using static Bunit.ComponentParameterFactory; - -namespace Bunit.Docs.Samples; - -public class AllKindsOfParamsTest : TestContext -{ - [Fact] - public void NonBlazorParamTypes() - { - // Using C# tuple with hardcoded name - var cut1 = Render( - ("Numbers", 42), - ("Lines", new List { "Hello", "World" }) - ); - - // Using C# tuple with refactor safe name - var cut2 = Render( - (nameof(NonBlazorTypesParams.Numbers), 42), - (nameof(NonBlazorTypesParams.Lines), new List { "Hello", "World" }) - ); - - // Using factory method - var cut3 = Render( - Parameter("Numbers", 42), - Parameter("Lines", new List { "Hello", "World" }) - ); - - // Using parameter builder - var cut4 = Render(parameters => parameters - .Add(p => p.Numbers, 42) - .Add(p => p.Lines, new List { "Hello", "World" }) - ); - } - - [Fact] - public void EventCallbackTypes() - { - - // Using factory method with hardcoded name - var cut1 = Render( - EventCallback("OnClick", (MouseEventArgs args) => - { - /* handle callback */ - }), - EventCallback("OnSomething", () => - { - /* handle callback */ - }) - ); - - // Using factory method refactor safe name - var cut2 = Render( - EventCallback(nameof(EventCallbackParams.OnClick), (MouseEventArgs args) => - { - /* handle callback */ - }), - EventCallback(nameof(EventCallbackParams.OnSomething), () => - { - /* handle callback */ - }) - ); - - // Using parameter builder - var cut3 = Render(parameters => parameters - .Add(p => p.OnClick, args => - { - /* handle callback */ - }) - .Add(p => p.OnSomething, () => - { - /* handle callback */ - }) - ); - } - - [Fact] - public void HtmlAsChildContent() - { - // Using factory method - var cut1 = Render( - ChildContent("

    Hello World

    ") - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddChildContent("

    Hello World

    ") - ); - } - - [Fact] - public void ComponentAsChildContent() - { - // Using factory method - var cut1 = Render( - ChildContent() - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddChildContent() - ); - } - - [Fact] - public void ComponentWithParamsAsChildContent() - { - // Using factory method - var cut1 = Render( - ChildContent( - ("Heading", "Alert heading"), - ("Type", AlertType.Warning), - ChildContent("

    Hello World

    ") - ) - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddChildContent(alertParameters => alertParameters - .Add(p => p.Heading, "Alert heading") - .Add(p => p.Type, AlertType.Warning) - .AddChildContent("

    Hello World

    ") - ) - ); - } - - [Fact] - public void ComponentAndMarkupAsChildContent() - { - // Using factory method - var cut1 = Render( - ChildContent("

    Below you will find a most interesting alert!

    "), - ChildContent( - ("Heading", "Alert heading"), - ("Type", AlertType.Warning), - ChildContent("

    Hello World

    ") - ) - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddChildContent("

    Below you will find a most interesting alert!

    ") - .AddChildContent(childParams => childParams - .Add(p => p.Heading, "Alert heading") - .Add(p => p.Type, AlertType.Warning) - .AddChildContent("

    Hello World

    ") - ) - ); - } - - [Fact] - public void HtmlAsRenderFragment() - { - // Using factory method - var cut1 = Render( - RenderFragment("Content", "

    Hello World

    ") - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .Add(p => p.Content, "

    Hello World

    ") - ); - } - - [Fact] - public void ComponentAsRenderFragment() - { - // Using factory method - var cut1 = Render( - RenderFragment("Content") - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .Add(p => p.Content) - ); - } - - [Fact] - public void ComponentWithParamsAsRenderFragment() - { - // Using factory method - var cut1 = Render( - RenderFragment("Content", - ("Heading", "Alert heading"), - ("Type", AlertType.Warning), - ChildContent("

    Hello World

    ") - ) - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .Add(p => p.Content, alertParameters => alertParameters - .Add(p => p.Heading, "Alert heading") - .Add(p => p.Type, AlertType.Warning) - .AddChildContent("

    Hello World

    ") - ) - ); - } - - [Fact] - public void ComponentAndMarkupAsRenderFragment() - { - // Using factory method - var cut1 = Render( - RenderFragment("Content", "

    Below you will find a most interesting alert!

    "), - RenderFragment("Content", - ("Heading", "Alert heading"), - ("Type", AlertType.Warning), - ChildContent("

    Hello World

    ") - ) - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .Add(p => p.Content, "

    Below you will find a most interesting alert!

    ") - .Add(p => p.Content, childParams => childParams - .Add(p => p.Heading, "Alert heading") - .Add(p => p.Type, AlertType.Warning) - .AddChildContent("

    Hello World

    ") - ) - ); - } - - [Fact] - public void HtmlTemplateParams() - { - // Using factory method - var cut1 = Render>( - ("Items", new string[] { "Foo", "Bar", "Baz" }), - Template("Template", item => $"{item}") - ); - - // Using parameter builder - var cut2 = Render>(parameters => parameters - .Add(p => p.Items, new[] { "Foo", "Bar", "Baz" }) - .Add(p => p.Template, item => $"{item}") - ); - } - - [Fact] - public void HtmlAndComponentTemplateParams() - { - // Using factory method - var cut1 = Render>( - ("Items", new string[] { "Foo", "Bar", "Baz" }), - Template("Template", value => new ComponentParameter[] - { - ("Value", value) - }) - ); - - // Using parameter builder - var cut2 = Render>(parameters => parameters - .Add(p => p.Items, new[] { "Foo", "Bar", "Baz" }) - .Add(p => p.Template, value => itemParams => itemParams - .Add(p => p.Value, value) - ) - ); - } - - [Fact] - public void UnmatchedParamsTest() - { - // Using factory method - var cut1 = Render( - ("some-unknown-param", "a value") - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddUnmatched("some-unknown-param", "a value") - ); - } - - [Fact] - public void UnnamedCascadingParamsTest() - { - var isDarkTheme = true; - - // Using factory method - var cut1 = Render( - CascadingValue(isDarkTheme) - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddCascadingValue(isDarkTheme) - ); - - // Using parameter builder and selecting unnamed cascading parameter - var cut3 = Render(parameters => parameters - .Add(p => p.IsDarkTheme, isDarkTheme) - ); - } - - [Fact] - public void NamedCascadingParamsTest() - { - // Using factory method - var cut1 = Render( - CascadingValue("LoggedInUser", "Egil Hansen") - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .Add(p => p.UserName, "Egil Hansen") - ); - } - - [Fact] - public void UnnamedAndNamedCascadingParamsTest() - { - var isDarkTheme = true; - - // Using factory method - var cut1 = Render( - CascadingValue(isDarkTheme), - CascadingValue("LoggedInUser", "Egil Hansen"), - CascadingValue("LoggedInEmail", "egil@example.com") - ); - - // Using parameter builder - var cut2 = Render(parameters => parameters - .AddCascadingValue(isDarkTheme) - .Add(p => p.UserName, "Egil Hansen") - .Add(p => p.Email, "egil@example.com") - ); - - // Using parameter builder and selecting unnamed cascading parameter - var cut3 = Render(parameters => parameters - .Add(p => p.IsDarkTheme, isDarkTheme) - .Add(p => p.UserName, "Egil Hansen") - .Add(p => p.Email, "egil@example.com") - ); - } -} \ No newline at end of file diff --git a/docs/samples/tests/xunit/NestedComponentTest.cs b/docs/samples/tests/xunit/NestedComponentTest.cs index 0db0b6fc0..ff18ec239 100644 --- a/docs/samples/tests/xunit/NestedComponentTest.cs +++ b/docs/samples/tests/xunit/NestedComponentTest.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using static Bunit.ComponentParameterFactory; namespace Bunit.Docs.Samples; diff --git a/docs/samples/tests/xunit/ReRenderTest.cs b/docs/samples/tests/xunit/ReRenderTest.cs index 18c9d0848..696a5c49f 100644 --- a/docs/samples/tests/xunit/ReRenderTest.cs +++ b/docs/samples/tests/xunit/ReRenderTest.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using static Bunit.ComponentParameterFactory; namespace Bunit.Docs.Samples; diff --git a/docs/samples/tests/xunit/SemanticHtmlTest.cs b/docs/samples/tests/xunit/SemanticHtmlTest.cs index e56455302..6ced88630 100644 --- a/docs/samples/tests/xunit/SemanticHtmlTest.cs +++ b/docs/samples/tests/xunit/SemanticHtmlTest.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using static Bunit.ComponentParameterFactory; namespace Bunit.Docs.Samples; diff --git a/docs/samples/tests/xunit/VerifyMarkupExamples.cs b/docs/samples/tests/xunit/VerifyMarkupExamples.cs index 9cf487f93..fb0c9b169 100644 --- a/docs/samples/tests/xunit/VerifyMarkupExamples.cs +++ b/docs/samples/tests/xunit/VerifyMarkupExamples.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; -using static Bunit.ComponentParameterFactory; namespace Bunit.Docs.Samples; diff --git a/docs/samples/tests/xunit/WeatherForecastsTest.cs b/docs/samples/tests/xunit/WeatherForecastsTest.cs index 824dd928c..c8a42a5c5 100644 --- a/docs/samples/tests/xunit/WeatherForecastsTest.cs +++ b/docs/samples/tests/xunit/WeatherForecastsTest.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.DependencyInjection; -using static Bunit.ComponentParameterFactory; namespace Bunit.Docs.Samples; diff --git a/docs/site/docs/interaction/trigger-renders.md b/docs/site/docs/interaction/trigger-renders.md index 7489af7c7..1e3461794 100644 --- a/docs/site/docs/interaction/trigger-renders.md +++ b/docs/site/docs/interaction/trigger-renders.md @@ -19,7 +19,7 @@ Let's look at how to use each of these methods to cause a re-render. The [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0})) method tells the renderer to re-render the component, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods). To use it, do the following: -[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=16&end=22&highlight=5)] +[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=15&end=21&highlight=5)] The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0})). @@ -30,7 +30,7 @@ The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponent The [`Render(...)`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods tells the renderer to re-render the component with new parameters, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods), passing the new parameters — _but only the new parameters_ — to the `SetParametersAsync()` method. To use it, do the following: -[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=29&end=39&highlight=7-9)] +[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=28&end=38&highlight=7-9)] The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})), which is also available as a version that takes the zero or more component parameters, e.g. created through the component parameter factory helper methods, if you prefer that method of passing parameters. @@ -51,7 +51,7 @@ Let’s look at an example of this, using the `` component listed below: To invoke the `Calculate()` method on the component instance, do the following: -[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=46&end=52&highlight=5)] +[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=45&end=51&highlight=5)] The highlighted line shows the call to `InvokeAsync()`, which is passed an `Action` delegate that calls the `Calculate` method. @@ -66,10 +66,10 @@ In some scenarios, the method being invoked may also return a value, as demonstr Testing this scenario follows the same procedure as before, with the addition of using the return value from `InvokeAsync()`: -[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=59&end=65&highlight=4)] +[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=58&end=64&highlight=4)] This can also be used to assert intermediate states during an asynchronous operation, like the example below: [!code-cshtml[CalcWithLoading.razor](../../../samples/components/CalcWithLoading.razor)] -[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=71&end=82&highlight=7)] +[!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=70&end=81&highlight=7)] diff --git a/docs/site/docs/providing-input/inject-services-into-components.md b/docs/site/docs/providing-input/inject-services-into-components.md index 2ab9f32a9..e9e1322f9 100644 --- a/docs/site/docs/providing-input/inject-services-into-components.md +++ b/docs/site/docs/providing-input/inject-services-into-components.md @@ -22,7 +22,7 @@ The following sections demonstrate how to do this. The examples we will cover wi Here is a test that registers the `IWeatherForecastService` in the `Services` collection, which is a requirement of the `` component listed above. -[!code-csharp[WeatherForecastsTest.cs](../../../samples/tests/xunit/WeatherForecastsTest.cs?start=17&end=25&highlight=2)] +[!code-csharp[WeatherForecastsTest.cs](../../../samples/tests/xunit/WeatherForecastsTest.cs?start=16&end=24&highlight=2)] The highlighted line shows how the `IWeatherForecastService` is registered in the test context's `Services` collection, which is just a standard [`IServiceCollection`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.iservicecollection), using the standard .NET Core dependency injection (DI) services method, [`AddSingleton`](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addsingleton?view=dotnet-plat-ext-3.1#Microsoft_Extensions_DependencyInjection_ServiceCollectionServiceExtensions_AddSingleton__1_Microsoft_Extensions_DependencyInjection_IServiceCollection___0_). diff --git a/docs/site/docs/providing-input/passing-parameters-to-components.md b/docs/site/docs/providing-input/passing-parameters-to-components.md index aa1832d10..a6455b5ab 100644 --- a/docs/site/docs/providing-input/passing-parameters-to-components.md +++ b/docs/site/docs/providing-input/passing-parameters-to-components.md @@ -375,7 +375,7 @@ It is possible to nest a component under tests inside other components, if that # [C# test code](#tab/csharp) -[!code-csharp[NestedComponentTest](../../../samples/tests/xunit/NestedComponentTest.cs#L11-L23)] +[!code-csharp[NestedComponentTest](../../../samples/tests/xunit/NestedComponentTest.cs#L11-L18)] The example renders the `` component inside the `` component. What is special in both cases is the use of the `FindComponent()` that returns a `RenderedComponent`. This is needed because the `Render` method call returns an `RenderedComponent` instance, that provides access to the instance of the `` component, but not the ``-component instance. diff --git a/docs/site/docs/verification/semantic-html-comparison.md b/docs/site/docs/verification/semantic-html-comparison.md index 0ef9bd5d0..38fe3b5f2 100644 --- a/docs/site/docs/verification/semantic-html-comparison.md +++ b/docs/site/docs/verification/semantic-html-comparison.md @@ -143,4 +143,4 @@ Let’s look at a few examples where we use the semantic comparison options list In this case, we want to verify that the markup is rendered correctly, using something such as RegEx to verify the `id` attribute (it might be generated) and ignoring the `` element. In tests we can do this like so with the `MarkupMatches()` method: -[!code-csharp[SemanticHtmlTest.cs](../../../samples/tests/xunit/SemanticHtmlTest.cs#L16-L28)] +[!code-csharp[SemanticHtmlTest.cs](../../../samples/tests/xunit/SemanticHtmlTest.cs#L15-L27)] diff --git a/docs/site/docs/verification/verify-markup.md b/docs/site/docs/verification/verify-markup.md index 0869f4fc8..147777e2e 100644 --- a/docs/site/docs/verification/verify-markup.md +++ b/docs/site/docs/verification/verify-markup.md @@ -99,13 +99,13 @@ In the following examples, the `` component listed below will be used a To use the `MarkupMatches()` method to perform a semantic comparison of the output of the `` component through its , do the following: -[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=25&end=30&highlight=3-6)] +[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=23&end=28&highlight=3-6)] The highlighted line shows the call to the `MarkupMatches()` method. This test passes even though the insignificant whitespace is not exactly the same between the expected HTML string and the raw markup produced by the `` component. It even works when the CSS class list is not in the same order on the `` element. The `MarkupMatches()` method is also available on `INode` and `INodeList` types, for example: -[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=36&end=39&highlight=3-4)] +[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=34&end=37&highlight=3-4)] Here we use the `Find(string cssSelector)` method to find the `` element, and only verify it and its content and attributes. @@ -114,7 +114,7 @@ Here we use the `Find(string cssSelector)` method to find the `` element, Text content can also be verified with the `MarkupMatches()` method, e.g. the text inside the `` element. It has the advantage over regular string comparison in that it removes insignificant whitespace in the text automatically - even between words - where a normal string `Trim()` method isn't enough. For example: -[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=45&end=48&highlight=3)] +[!code-csharp[](../../../samples/tests/xunit/VerifyMarkupExamples.cs?start=43&end=46&highlight=3)] The semantic HTML comparer can be customized to make a test case even more stable and easier to maintain. For example, it is possible to ignore an element or attribute during comparison, or provide a regular expression to the comparer when comparing a specific element or attribute to make the comparer work with generated data. diff --git a/src/bunit/ComponentParameter.cs b/src/bunit/ComponentParameter.cs index 7d3aa2ccc..4215488b6 100644 --- a/src/bunit/ComponentParameter.cs +++ b/src/bunit/ComponentParameter.cs @@ -5,7 +5,7 @@ namespace Bunit; /// component under test. ///
    [SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "No need in this case.")] -public readonly struct ComponentParameter : IEquatable +internal readonly record struct ComponentParameter { /// /// Gets the name of the parameter. Can be null if the parameter is for an unnamed cascading value. @@ -75,25 +75,6 @@ public static implicit operator ComponentParameter((string Name, object? Value) public static implicit operator ComponentParameter((string? Name, object? Value, bool IsCascadingValue) input) => new ComponentParameter(input.Name, input.Value, input.IsCascadingValue); - /// - public bool Equals(ComponentParameter other) - => string.Equals(Name, other.Name, StringComparison.Ordinal) - && ((Value is null && other.Value is null) || (Value?.Equals(other.Value) ?? false)) - && IsCascadingValue.Equals(other.IsCascadingValue); - - /// - public override bool Equals(object? obj) => obj is ComponentParameter other && Equals(other); - /// public override int GetHashCode() => HashCode.Combine(Name, Value, IsCascadingValue); - - /// - /// Verify whether the and are equal. - /// - public static bool operator ==(ComponentParameter left, ComponentParameter right) => left.Equals(right); - - /// - /// Verify whether the and are not equal. - /// - public static bool operator !=(ComponentParameter left, ComponentParameter right) => !(left == right); } diff --git a/src/bunit/ComponentParameterCollection.cs b/src/bunit/ComponentParameterCollection.cs index 86fb0b81e..9b144e693 100644 --- a/src/bunit/ComponentParameterCollection.cs +++ b/src/bunit/ComponentParameterCollection.cs @@ -5,7 +5,7 @@ namespace Bunit; /// /// A collection for . /// -public class ComponentParameterCollection : ICollection, IReadOnlyCollection +internal class ComponentParameterCollection : ICollection, IReadOnlyCollection { private static readonly MethodInfo CreateTemplateWrapperMethod = GetCreateTemplateWrapperMethod(); private static readonly Type CascadingValueType = typeof(CascadingValue<>); diff --git a/src/bunit/ComponentParameterCollectionBuilder.cs b/src/bunit/ComponentParameterCollectionBuilder.cs index c088c2717..f1bbf142a 100644 --- a/src/bunit/ComponentParameterCollectionBuilder.cs +++ b/src/bunit/ComponentParameterCollectionBuilder.cs @@ -422,7 +422,7 @@ public bool TryAdd(string name, [AllowNull] TValue value) /// Builds the . /// /// The created . - public ComponentParameterCollection Build() => parameters; + internal ComponentParameterCollection Build() => parameters; private static (string Name, string? CascadingValueName, bool IsCascading) GetParameterInfo( Expression> parameterSelector, object? value diff --git a/src/bunit/ComponentParameterFactory.cs b/src/bunit/ComponentParameterFactory.cs deleted file mode 100644 index 668a8c65f..000000000 --- a/src/bunit/ComponentParameterFactory.cs +++ /dev/null @@ -1,242 +0,0 @@ -using Bunit.Extensions; - -namespace Bunit; - -/// -/// factory methods. -/// -public static class ComponentParameterFactory -{ - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The . - public static ComponentParameter EventCallback(string name, Action callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The . - public static ComponentParameter EventCallback(string name, Action callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The . - public static ComponentParameter EventCallback(string name, Func callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The . - public static ComponentParameter EventCallback(string name, Func callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The value returned in the . - /// The . - public static ComponentParameter EventCallback(string name, Action callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The value returned in the . - /// The . - public static ComponentParameter EventCallback(string name, Action callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The value returned in the . - /// The . - public static ComponentParameter EventCallback(string name, Func callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a with an that will call the provided . - /// - /// Parameter name. - /// The event callback. - /// The value returned in the . - /// The . - public static ComponentParameter EventCallback(string name, Func callback) - { - return ComponentParameter.CreateParameter(name, new EventCallback(receiver: null, callback)); - } - - /// - /// Creates a component parameter which can be passed to a test contexts render methods. - /// - /// Parameter name. - /// Value or null of the parameter. - /// The . - public static ComponentParameter Parameter(string name, object? value) - { - return ComponentParameter.CreateParameter(name, value); - } - - /// - /// Creates a cascading value which can be passed to a test contexts render methods. - /// - /// Parameter name. - /// Value of the parameter. - /// The . - public static ComponentParameter CascadingValue(string name, object value) - { - return ComponentParameter.CreateCascadingValue(name, value); - } - - /// - /// Creates a cascading value which can be passed to a test contexts render methods. - /// - /// Value of the parameter. - /// The . - public static ComponentParameter CascadingValue(object value) - { - return ComponentParameter.CreateCascadingValue(name: null, value); - } - - /// - /// Creates a ChildContent with the provided - /// as rendered output. - /// - /// Markup to pass to the child content parameter. - /// The . - public static ComponentParameter ChildContent([StringSyntax("Html")]string markup) - { - return RenderFragment(nameof(ChildContent), markup); - } - - /// - /// Creates a ChildContent which will render a component - /// with the provided as input. - /// - /// The type of the component to render with the . - /// Parameters to pass to the . - /// The . - public static ComponentParameter ChildContent(params ComponentParameter[] parameters) - where TComponent : class, IComponent - { - return RenderFragment(nameof(ChildContent), parameters); - } - - /// - /// Creates a ChildContent parameter that will pass the provided - /// to the parameter in the component. - /// - /// The to pass to the ChildContent parameter. - /// The . - public static ComponentParameter ChildContent(RenderFragment renderFragment) - { - return Parameter(nameof(ChildContent), renderFragment); - } - - /// - /// Creates a with the provided - /// as rendered output and passes it to the parameter specified in . - /// - /// Parameter name. - /// Markup to pass to the render fragment parameter. - /// The . - public static ComponentParameter RenderFragment(string name, [StringSyntax("Html")]string markup) - { - return ComponentParameter.CreateParameter(name, markup.ToMarkupRenderFragment()); - } - - /// - /// Creates a which will render a component - /// with the provided as input, and passes it to the parameter specified in . - /// - /// The type of the component to render with the . - /// Parameter name. - /// Parameters to pass to the . - /// The . - public static ComponentParameter RenderFragment(string name, params ComponentParameter[] parameters) - where TComponent : class, IComponent - { - var cpc = new ComponentParameterCollection { parameters }; - return ComponentParameter.CreateParameter(name, cpc.ToRenderFragment()); - } - - /// - /// Creates a template component parameter which will pass the - /// to the parameter with the name . - /// - /// The value used to build the content. - /// Parameter name. - /// to pass to the parameter. - /// The . - public static ComponentParameter Template(string name, RenderFragment template) - { - return ComponentParameter.CreateParameter(name, template); - } - - /// - /// Creates a template component parameter which will pass the a - /// to the parameter with the name . - /// The will be used to generate the markup inside the template. - /// - /// The value used to build the content. - /// Parameter name. - /// A markup factory that takes a as input and returns markup/HTML. - /// The . - public static ComponentParameter Template(string name, Func markupFactory) - { - return Template(name, value => builder => builder.AddMarkupContent(0, markupFactory(value))); - } - - /// - /// Creates a template component parameter which will pass the a - /// to the at runtime. The parameters returned from it - /// will be passed to the and it will be rendered as the template. - /// - /// The type of component to render in template. - /// The value used to build the content. - /// Parameter name. - /// The parameter collection builder function that will be passed the template . - /// The . - public static ComponentParameter Template(string name, Func parameterCollectionBuilder) - where TComponent : IComponent - { - return Template(name, value => - { - var cpc = new ComponentParameterCollection { parameterCollectionBuilder(value) }; - return cpc.ToRenderFragment(); - }); - } -} diff --git a/src/bunit/Extensions/BunitRendererExtensions.cs b/src/bunit/Extensions/BunitRendererExtensions.cs index 2ef8a7473..0cdceb9bc 100644 --- a/src/bunit/Extensions/BunitRendererExtensions.cs +++ b/src/bunit/Extensions/BunitRendererExtensions.cs @@ -8,25 +8,6 @@ namespace Bunit.Extensions; /// public static class BunitRendererExtensions { - /// - /// Renders a with the parameters passed to it. - /// - /// The type of component to render. - /// The renderer to use. - /// The parameters to pass to the component. - /// A that provides access to the rendered component. - public static RenderedComponent Render(this BunitRenderer renderer, params ComponentParameter[] parameters) - where TComponent : IComponent - { - ArgumentNullException.ThrowIfNull(renderer); - - var resultBase = renderer.Render(new ComponentParameterCollection { parameters }); - if (resultBase is RenderedComponent result) - return result; - - throw new InvalidOperationException($"The renderer did not produce the expected type."); - } - /// /// Renders a with the parameters build with the passed to it. /// @@ -34,17 +15,14 @@ public static RenderedComponent Render(this BunitRendere /// The renderer to use. /// The a builder to create parameters to pass to the component. /// A that provides access to the rendered component. - public static RenderedComponent Render(this BunitRenderer renderer, Action> parameterBuilder) + public static RenderedComponent Render(this BunitRenderer renderer, Action>? parameterBuilder = null) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderer); - ArgumentNullException.ThrowIfNull(parameterBuilder); var builder = new ComponentParameterCollectionBuilder(parameterBuilder); - var resultBase = renderer.Render(builder.Build()); - if (resultBase is RenderedComponent result) - return result; - - throw new InvalidOperationException($"The renderer did not produce the expected type."); + var renderFragment = builder.Build().ToRenderFragment(); + var renderedFragment = renderer.RenderFragment(renderFragment); + return renderedFragment.FindComponent(); } } diff --git a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs index bc74ee5d1..b231e4710 100644 --- a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs @@ -7,15 +7,6 @@ namespace Bunit; /// public static class RenderedComponentRenderExtensions { - /// - /// Render the component under test again. - /// - /// The rendered component to re-render. - /// The type of the component. - public static void Render(this RenderedComponent renderedComponent) - where TComponent : IComponent - => Render(renderedComponent, ParameterView.Empty); - /// /// Render the component under test again with the provided . /// @@ -39,38 +30,22 @@ public static void Render(this RenderedComponent rendere } } - /// - /// Render the component under test again with the provided . - /// - /// The rendered component to re-render with new parameters. - /// Parameters to pass to the component upon rendered. - /// The type of the component. - public static void Render(this RenderedComponent renderedComponent, params ComponentParameter[] parameters) - where TComponent : IComponent - { - ArgumentNullException.ThrowIfNull(renderedComponent); - ArgumentNullException.ThrowIfNull(parameters); - - Render(renderedComponent, ToParameterView(parameters)); - } - /// /// Render the component under test again with the provided parameters from the . /// /// The rendered component to re-render with new parameters. /// An action that receives a . /// The type of the component. - public static void Render(this RenderedComponent renderedComponent, Action> parameterBuilder) + public static void Render(this RenderedComponent renderedComponent, Action>? parameterBuilder = null) where TComponent : IComponent { ArgumentNullException.ThrowIfNull(renderedComponent); - ArgumentNullException.ThrowIfNull(parameterBuilder); var builder = new ComponentParameterCollectionBuilder(parameterBuilder); Render(renderedComponent, ToParameterView(builder.Build())); } - private static ParameterView ToParameterView(IReadOnlyCollection parameters) + private static ParameterView ToParameterView(ComponentParameterCollection parameters) { var parameterView = ParameterView.Empty; diff --git a/src/bunit/Rendering/BunitRenderer.cs b/src/bunit/Rendering/BunitRenderer.cs index 661f4bb68..d91d67d1b 100644 --- a/src/bunit/Rendering/BunitRenderer.cs +++ b/src/bunit/Rendering/BunitRenderer.cs @@ -84,21 +84,6 @@ public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory, public RenderedFragment RenderFragment(RenderFragment renderFragment) => Render(renderFragment); - /// - /// Renders a with the passed to it. - /// - /// The type of component to render. - /// The parameters to pass to the component. - /// A that provides access to the rendered component. - public RenderedComponent Render(ComponentParameterCollection parameters) - where TComponent : IComponent - { - ArgumentNullException.ThrowIfNull(parameters); - - var renderFragment = parameters.ToRenderFragment(); - return Render(renderFragment).FindComponent(); - } - /// /// Notifies the renderer that an event has occurred. /// diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 06e5dfe9f..59daeeeec 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -117,21 +117,6 @@ public void DisposeComponents() Renderer.DisposeComponents(); } - /// - /// Instantiates and performs a first render of a component of type . - /// - /// Type of the component to render. - /// Parameters to pass to the component when it is rendered. - /// The rendered . - public virtual RenderedComponent Render(params ComponentParameter[] parameters) - where TComponent : IComponent - { - var renderFragment = new ComponentParameterCollection { parameters } - .ToRenderFragment(); - - return Render(renderFragment); - } - /// /// Instantiates and performs a first render of a component of type . /// diff --git a/src/bunit/TestContextWrapper.cs b/src/bunit/TestContextWrapper.cs index ad38f7cec..8fbbf14e7 100644 --- a/src/bunit/TestContextWrapper.cs +++ b/src/bunit/TestContextWrapper.cs @@ -37,23 +37,13 @@ public abstract class TestContextWrapper /// public BunitJSInterop JSInterop => TestContext?.JSInterop ?? throw new InvalidOperationException("The TestContext has not been initialized."); - /// - /// Instantiates and performs a first render of a component of type . - /// - /// Type of the component to render. - /// Parameters to pass to the component when it is rendered. - /// The rendered . - public virtual RenderedComponent Render(params ComponentParameter[] parameters) - where TComponent : IComponent - => TestContext?.Render(parameters) ?? throw new InvalidOperationException("The TestContext has not been initialized."); - /// /// Instantiates and performs a first render of a component of type . /// /// Type of the component to render. /// The ComponentParameterBuilder action to add type safe parameters to pass to the component when it is rendered. /// The rendered . - public virtual RenderedComponent Render(Action> parameterBuilder) + public virtual RenderedComponent Render(Action>? parameterBuilder = null) where TComponent : IComponent => TestContext?.Render(parameterBuilder) ?? throw new InvalidOperationException("The TestContext has not been initialized."); diff --git a/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs index 8bd875058..cef1b5fc8 100644 --- a/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs +++ b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs @@ -1,4 +1,3 @@ -using AngleSharp.Dom; using Bunit.TestUtilities; namespace Bunit; @@ -41,8 +40,8 @@ public void Test001(MethodInfo methodInfo, string argName, object[] args) [Fact(DisplayName = "CompareTo with rendered fragment and string")] public void Test002() { - var rf1 = Render((nameof(Simple1.Header), "FOO")); - var rf2 = Render((nameof(Simple1.Header), "BAR")); + var rf1 = Render(ps => ps.Add(p => p.Header, "FOO")); + var rf2 = Render(ps => ps.Add(p => p.Header, "BAR")); rf1.CompareTo(rf2.Markup).Count.ShouldBe(1); } @@ -50,8 +49,8 @@ public void Test002() [Fact(DisplayName = "CompareTo with rendered fragment and rendered fragment")] public void Test003() { - var rf1 = Render((nameof(Simple1.Header), "FOO")); - var rf2 = Render((nameof(Simple1.Header), "BAR")); + var rf1 = Render(ps => ps.Add(p => p.Header, "FOO")); + var rf2 = Render(ps => ps.Add(p => p.Header, "BAR")); rf1.CompareTo(rf2).Count.ShouldBe(1); } @@ -59,8 +58,8 @@ public void Test003() [Fact(DisplayName = "CompareTo with INode and INodeList")] public void Test004() { - var rf1 = Render((nameof(Simple1.Header), "FOO")); - var rf2 = Render((nameof(Simple1.Header), "BAR")); + var rf1 = Render(ps => ps.Add(p => p.Header, "FOO")); + var rf2 = Render(ps => ps.Add(p => p.Header, "BAR")); var elm = rf1.Find("h1"); elm.CompareTo(rf2.Nodes).Count.ShouldBe(1); @@ -69,26 +68,11 @@ public void Test004() [Fact(DisplayName = "CompareTo with INodeList and INode")] public void Test005() { - var rf1 = Render((nameof(Simple1.Header), "FOO")); - var rf2 = Render((nameof(Simple1.Header), "BAR")); + var rf1 = Render(ps => ps.Add(p => p.Header, "FOO")); + var rf2 = Render(ps => ps.Add(p => p.Header, "BAR")); var elm = rf1.Find("h1"); rf2.Nodes.CompareTo(elm).Count.ShouldBe(1); } - - private static int GetPathIndex(INode node) - { - var parent = node.Parent; - if (parent is not null) - { - var childNodes = parent.ChildNodes; - for (int index = 0; index < childNodes.Length; index++) - { - if (ReferenceEquals(childNodes[index], node)) - return index; - } - } - throw new InvalidOperationException("Unexpected node tree state. The node was not found in its parents child nodes collection."); - } } diff --git a/tests/bunit.tests/ComponentParameterFactoryTest.cs b/tests/bunit.tests/ComponentParameterFactoryTest.cs deleted file mode 100644 index 0f7d65adb..000000000 --- a/tests/bunit.tests/ComponentParameterFactoryTest.cs +++ /dev/null @@ -1,277 +0,0 @@ -using static Bunit.ComponentParameterFactory; - -namespace Bunit; - -public class ComponentParameterFactoryTest -{ - private const string NAME = nameof(NAME); - private const string EXPECTED = nameof(EXPECTED); - private static readonly TestContext Context = new(); - - private static RenderedFragment RenderWithRenderFragment(RenderFragment renderFragment) - { - return Context.Renderer.RenderFragment(renderFragment); - } - - private string? Actual { get; set; } - - [Fact(DisplayName = "EventCallback(Action) creates parameter with provided name and callback")] - public async Task Test001() - { - Action action = () => Actual = EXPECTED; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Action) creates parameter with provided name and callback")] - public async Task Test002() - { - Action action = _ => Actual = EXPECTED; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Func) creates parameter with provided name and callback")] - public async Task Test003() - { - Func action = () => { Actual = EXPECTED; return Task.CompletedTask; }; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Func) creates parameter with provided name and callback")] - public async Task Test004() - { - Func action = _ => { Actual = EXPECTED; return Task.CompletedTask; }; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Action) creates parameter with provided name and callback")] - public async Task Test011() - { - Action action = () => Actual = EXPECTED; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Action) creates parameter with provided name and callback")] - public async Task Test012() - { - Action action = _ => Actual = EXPECTED; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Func) creates parameter with provided name and callback")] - public async Task Test013() - { - Func action = () => { Actual = EXPECTED; return Task.CompletedTask; }; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - [Fact(DisplayName = "EventCallback(Func) creates parameter with provided name and callback")] - public async Task Test014() - { - Func action = _ => { Actual = EXPECTED; return Task.CompletedTask; }; - - var cp = EventCallback(NAME, action); - - await VerifyEventCallbackParameter(cp); - } - - private async Task VerifyEventCallbackParameter(ComponentParameter cp) - { - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - await cp.Value.ShouldBeOfType().InvokeAsync(EventArgs.Empty); - Actual.ShouldBe(EXPECTED); - } - - private async Task VerifyEventCallbackParameter(ComponentParameter cp) - where TCallbackType : new() - { - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - await cp.Value.ShouldBeOfType>().InvokeAsync(new TCallbackType()); - Actual.ShouldBe(EXPECTED); - } - - [Fact(DisplayName = "Parameter creates a parameter with provided name and value")] - public void Test020() - { - var cp = Parameter(NAME, EXPECTED); - - cp.Name.ShouldBe(NAME); - cp.Value.ShouldBe(EXPECTED); - cp.IsCascadingValue.ShouldBeFalse(); - } - - [Fact(DisplayName = "Parameter creates a parameter with provided name and null value")] - public void Test021() - { - var cp = Parameter(NAME, null); - - cp.Name.ShouldBe(NAME); - cp.Value.ShouldBeNull(); - cp.IsCascadingValue.ShouldBeFalse(); - } - - [Fact(DisplayName = "CascadingValue(name, value) creates a named cascading value parameter with provided name and value")] - public void Test030() - { - var cp = CascadingValue(NAME, EXPECTED); - - cp.Name.ShouldBe(NAME); - cp.Value.ShouldBe(EXPECTED); - cp.IsCascadingValue.ShouldBeTrue(); - } - - [Fact(DisplayName = "CascadingValue(name, value) creates a unnamed cascading value parameter with provided name and value")] - public void Test031() - { - var cp = CascadingValue(EXPECTED); - - cp.Name.ShouldBeNull(); - cp.Value.ShouldBe(EXPECTED); - cp.IsCascadingValue.ShouldBeTrue(); - } - - [Fact(DisplayName = "ChildContent(string markup) creates a parameter with a RenderFragment that renders the provided markup")] - public void Test040() - { - var cp = ChildContent(EXPECTED); - - cp.Name.ShouldBe("ChildContent"); - cp.IsCascadingValue.ShouldBeFalse(); - var renderFragment = cp.Value.ShouldBeOfType(); - var renderedFragment = RenderWithRenderFragment(renderFragment); - renderedFragment.Markup.ShouldBe(EXPECTED); - } - - [Fact(DisplayName = "ChildContent() creates a parameter with a RenderFragment that renders a component of type TComponent")] - public void Test041() - { - var cp = ChildContent(); - - cp.Name.ShouldBe("ChildContent"); - cp.IsCascadingValue.ShouldBeFalse(); - var renderFragment = cp.Value.ShouldBeOfType(); - var renderedFragment = RenderWithRenderFragment(renderFragment); - renderedFragment.Markup.ShouldBe(nameof(TestComponent)); - } - - [Fact(DisplayName = "ChildContent(component parameters) creates a parameter with a RenderFragment that renders a component of type TComponent")] - public void Test042() - { - var cp = ChildContent((nameof(TestComponent.Input), EXPECTED)); - - cp.Name.ShouldBe("ChildContent"); - cp.IsCascadingValue.ShouldBeFalse(); - var renderFragment = cp.Value.ShouldBeOfType(); - var renderedFragment = RenderWithRenderFragment(renderFragment); - renderedFragment.Markup.ShouldBe(nameof(TestComponent) + EXPECTED); - } - - [Fact(DisplayName = "ChildContent(RenderFragment) creates a parameter with a RenderFragment passed to ChildContent")] - public void Test043() - { - var cp = ChildContent(b => b.AddMarkupContent(0, EXPECTED)); - - cp.Name.ShouldBe("ChildContent"); - cp.IsCascadingValue.ShouldBeFalse(); - var renderFragment = cp.Value.ShouldBeOfType(); - var renderedFragment = RenderWithRenderFragment(renderFragment); - renderedFragment.Markup.ShouldBe(EXPECTED); - } - - [Fact(DisplayName = "RenderFragment(name, markup) creates a parameter with a RenderFragment that renders a component of type TComponent")] - public void Test051() - { - var cp = RenderFragment(NAME, EXPECTED); - - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - var renderFragment = cp.Value.ShouldBeOfType(); - var renderedFragment = RenderWithRenderFragment(renderFragment); - renderedFragment.Markup.ShouldBe(EXPECTED); - } - - [Fact(DisplayName = "RenderFragment(name, component parameters) creates a parameter with a RenderFragment that renders a component of type TComponent")] - public void Test052() - { - var cp = RenderFragment(NAME, (nameof(TestComponent.Input), EXPECTED)); - - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - var renderFragment = cp.Value.ShouldBeOfType(); - var renderedFragment = RenderWithRenderFragment(renderFragment); - renderedFragment.Markup.ShouldBe(nameof(TestComponent) + EXPECTED); - } - - [Fact(DisplayName = "Template(string, RenderFragment) creates a parameter with a Template")] - public void Test061() - { - var cp = Template(NAME, s => b => b.AddMarkupContent(0, s)); - - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - var template = cp.Value.ShouldBeOfType>(); - var renderedFragment = RenderWithRenderFragment(template(EXPECTED)); - renderedFragment.Markup.ShouldBe(EXPECTED); - } - - [Fact(DisplayName = "Template(string, Func) creates a parameter with a Template")] - public void Test062() - { - var cp = Template(NAME, s => s); - - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - var template = cp.Value.ShouldBeOfType>(); - var renderedFragment = RenderWithRenderFragment(template(EXPECTED)); - renderedFragment.Markup.ShouldBe(EXPECTED); - } - - [Fact(DisplayName = "Template(string, Func) creates a parameter with a Template")] - public void Test063() - { - var cp = Template(NAME, value => new ComponentParameter[] - { - (nameof(TestComponent.Input), value), - }); - - cp.Name.ShouldBe(NAME); - cp.IsCascadingValue.ShouldBeFalse(); - var template = cp.Value.ShouldBeOfType>(); - var renderedFragment = RenderWithRenderFragment(template(EXPECTED)); - renderedFragment.Markup.ShouldBe(nameof(TestComponent) + EXPECTED); - } - - private sealed class TestComponent : ComponentBase - { - [Parameter] public string? Input { get; set; } - [Parameter] public RenderFragment? Template { get; set; } - - protected override void BuildRenderTree(RenderTreeBuilder builder) - { - builder.AddMarkupContent(0, nameof(TestComponent)); - builder.AddMarkupContent(1, Input); - } - } -} diff --git a/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs index ec5688a44..5a1f158f1 100644 --- a/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs @@ -15,11 +15,11 @@ protected EventDispatchExtensionsTest(ITestOutputHelper outputHelper) } protected TriggerEventSpy CreateTriggerSpy(string element, string eventName) - => new(p => Render>(p), element, eventName); + => new(Render, element, eventName); // This is a separate overload for useful in non-reflection based testing protected TriggerEventSpy CreateTriggerSpy(string element, string eventName) where T : EventArgs, new() - => new(p => Render>(p), element, eventName); + => new(Render, element, eventName); protected void VerifyEventRaisesCorrectly(MethodInfo helper, TEventArgs expected, params (string MethodName, string EventName)[] methodNameEventMap) { diff --git a/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs b/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs index 20473eabd..ae17ed612 100644 --- a/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs +++ b/tests/bunit.tests/EventDispatchExtensions/TriggerEventSpy.cs @@ -11,16 +11,17 @@ public class TriggerEventSpy public TEventArgs RaisedEvent => receivedEvent!; - public TriggerEventSpy(Func>> componentRenderer, string element, string eventName) + public TriggerEventSpy( + Func>>, + RenderedComponent>> componentRenderer, string element, string eventName) { ArgumentNullException.ThrowIfNull(componentRenderer); - renderedComponent = componentRenderer(new ComponentParameter[] - { - (nameof(TriggerTester.Element), element), - (nameof(TriggerTester.EventName), eventName), - (nameof(TriggerTester.TriggeredEvent), EventCallback.Factory.Create(this, CallbackHandler)), - }); + renderedComponent = componentRenderer(ps => ps + .Add(p => p.Element, element) + .Add(p => p.EventName, eventName) + .Add(p => p.TriggeredEvent, EventCallback.Factory.Create(this, CallbackHandler))); + this.element = element; } diff --git a/tests/bunit.tests/Rendering/BunitRendererTests.cs b/tests/bunit.tests/Rendering/BunitRendererTests.cs index cb6c4cb7d..caf52697d 100644 --- a/tests/bunit.tests/Rendering/BunitRendererTests.cs +++ b/tests/bunit.tests/Rendering/BunitRendererTests.cs @@ -1,6 +1,5 @@ using Bunit.Extensions; using Bunit.TestAssets.RenderModes; -using static Bunit.ComponentParameterFactory; namespace Bunit.Rendering; @@ -54,7 +53,7 @@ public void Test005() { const string VALUE = "FOO BAR"; - var cut = Renderer.Render((nameof(HasParams.Value), VALUE)); + var cut = Renderer.Render(ps => ps.Add(p => p.Value, VALUE)); cut.Instance.Value.ShouldBe(VALUE); } @@ -65,9 +64,9 @@ public void Test006() const string PARENT_VALUE = "PARENT"; const string CHILD_VALUE = "CHILD"; - var cut = Renderer.Render( - (nameof(HasParams.Value), PARENT_VALUE), - ChildContent((nameof(HasParams.Value), CHILD_VALUE))); + var cut = Renderer.Render(ps => ps + .Add(p => p.Value, PARENT_VALUE) + .AddChildContent(pps => pps.Add(p => p.Value, CHILD_VALUE))); cut.Markup.ShouldStartWith(PARENT_VALUE); cut.Markup.ShouldEndWith(CHILD_VALUE); @@ -109,9 +108,9 @@ public void Test020() const string PARENT_VALUE = "PARENT"; const string CHILD_VALUE = "CHILD"; - var cut = Renderer.Render( - (nameof(HasParams.Value), PARENT_VALUE), - ChildContent((nameof(HasParams.Value), CHILD_VALUE))); + var cut = Renderer.Render(ps => ps + .Add(p => p.Value, PARENT_VALUE) + .AddChildContent(pps => pps.Add(p => p.Value, CHILD_VALUE))); // act var childCut = Renderer.FindComponent(cut); @@ -138,8 +137,8 @@ public void Test022() [Fact(DisplayName = "FindComponent returns same rendered component when called multiple times")] public void Test023() { - var cut = Renderer.Render( - ChildContent()); + var cut = Renderer.Render(ps => ps + .AddChildContent()); var child1 = Renderer.FindComponent(cut); var child2 = Renderer.FindComponent(cut); @@ -155,12 +154,12 @@ public void Test030() const string PARENT_VALUE = nameof(PARENT_VALUE); const string CHILD_VALUE = nameof(CHILD_VALUE); - var cut = Renderer.Render( - (nameof(HasParams.Value), GRAND_PARENT_VALUE), - ChildContent( - (nameof(HasParams.Value), PARENT_VALUE), - ChildContent( - (nameof(HasParams.Value), CHILD_VALUE)))); + var cut = Renderer.Render(ps => ps + .Add(p => p.Value, GRAND_PARENT_VALUE) + .AddChildContent(pps => pps + .Add(p => p.Value, PARENT_VALUE) + .AddChildContent(ppps => ppps + .Add(p=>p.Value, CHILD_VALUE)))); // act var childCuts = Renderer.FindComponents(cut) @@ -185,9 +184,9 @@ public void Test031() public void Test032() { // arrange - var cut = Renderer.Render( - ChildContent( - ChildContent())); + var cut = Renderer.Render(ps => ps + .AddChildContent(pps => pps + .AddChildContent())); // act var childCuts1 = Renderer.FindComponents(cut); @@ -200,8 +199,8 @@ public void Test032() [Fact(DisplayName = "Retrieved rendered child component with FindComponent gets updated on re-render")] public async Task Test040() { - var parent = Renderer.Render( - ChildContent()); + var parent = Renderer.Render(ps => ps + .AddChildContent()); // act var cut = Renderer.FindComponent(parent); @@ -217,8 +216,8 @@ public async Task Test040() [Fact(DisplayName = "Retrieved rendered child component with FindComponents gets updated on re-render")] public async Task Test041() { - var parent = Renderer.Render( - ChildContent()); + var parent = Renderer.Render(ps => ps + .AddChildContent()); // act var cut = Renderer.FindComponents(parent).Single(); @@ -235,8 +234,8 @@ public async Task Test041() public async Task Test050() { // arrange - var cut = Renderer.Render( - ChildContent()); + var cut = Renderer.Render(ps => ps + .AddChildContent()); var child = Renderer.FindComponent(cut); // act @@ -251,8 +250,8 @@ public async Task Test050() public async Task Test060() { // arrange - var cut = Renderer.Render( - ChildContent()); + var cut = Renderer.Render(ps => ps + .AddChildContent()); var child = Renderer.FindComponent(cut); // act @@ -267,9 +266,9 @@ public async Task Test060() public async Task Test061() { // arrange - var cut = Renderer.Render( - ChildContent( - ChildContent())); + var cut = Renderer.Render(ps => ps + .AddChildContent(pps => pps + .AddChildContent())); var child = Renderer.FindComponent(cut); var childChild = Renderer.FindComponent(cut); diff --git a/tests/bunit.tests/Rendering/ComponentParameterTest.cs b/tests/bunit.tests/Rendering/ComponentParameterTest.cs index 26458c101..7a8d198ee 100644 --- a/tests/bunit.tests/Rendering/ComponentParameterTest.cs +++ b/tests/bunit.tests/Rendering/ComponentParameterTest.cs @@ -2,62 +2,15 @@ namespace Bunit.Rendering; public class ComponentParameterTest { - public static IEnumerable GetEqualsTestData() - { - var name = "foo"; - var value = "bar"; - var p1 = ComponentParameter.CreateParameter(name, value); - var p2 = ComponentParameter.CreateParameter(name, value); - var p3 = ComponentParameter.CreateCascadingValue(name, value); - var p4 = ComponentParameter.CreateParameter(string.Empty, value); - var p5 = ComponentParameter.CreateParameter(name, string.Empty); - - yield return new object[] { p1, p1, true }; - yield return new object[] { p1, p2, true }; - yield return new object[] { p3, p3, true }; - yield return new object[] { p1, p3, false }; - yield return new object[] { p1, p4, false }; - yield return new object[] { p1, p5, false }; - } - [Fact(DisplayName = "Creating a cascading value with null throws")] public void Test001() { Should.Throw(() => ComponentParameter.CreateCascadingValue(null, null!)); - Should.Throw(() => (ComponentParameter)(null, null, true)); } [Fact(DisplayName = "Creating a regular parameter without a name throws")] public void Test002() { Should.Throw(() => ComponentParameter.CreateParameter(null!, null)); - Should.Throw(() => (ComponentParameter)(null, null, false)); - } - - [Theory(DisplayName = "Equals compares correctly")] - [MemberData(nameof(GetEqualsTestData))] - public void Test003(ComponentParameter left, ComponentParameter right, bool expectedResult) - { - left.Equals(right).ShouldBe(expectedResult); - right.Equals(left).ShouldBe(expectedResult); - (left == right).ShouldBe(expectedResult); - (left != right).ShouldNotBe(expectedResult); - left.Equals((object)right).ShouldBe(expectedResult); - right.Equals((object)left).ShouldBe(expectedResult); - } - - [Fact(DisplayName = "Equals operator works as expected with non compatible types")] - public void Test004() - { - ComponentParameter.CreateParameter(string.Empty, string.Empty) - .Equals(new object()) - .ShouldBeFalse(); - } - - [Theory(DisplayName = "GetHashCode returns same result for equal ComponentParameter")] - [MemberData(nameof(GetEqualsTestData))] - public void Test005(ComponentParameter left, ComponentParameter right, bool expectedResult) - { - left.GetHashCode().Equals(right.GetHashCode()).ShouldBe(expectedResult); } } diff --git a/tests/bunit.tests/Rendering/RenderedComponentTest.cs b/tests/bunit.tests/Rendering/RenderedComponentTest.cs index ece1dd8c6..3853e1f32 100644 --- a/tests/bunit.tests/Rendering/RenderedComponentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedComponentTest.cs @@ -30,7 +30,7 @@ public void Test0041() { var cut = Render(parameters => parameters.AddChildContent("
    ")); - cut.Render(ComponentParameterFactory.ChildContent("

    ")); + cut.Render(ps => ps.AddChildContent("

    ")); cut.Find("p").ShouldNotBeNull(); } diff --git a/tests/bunit.tests/Rendering/RenderedFragmentTest.cs b/tests/bunit.tests/Rendering/RenderedFragmentTest.cs index a03d889a9..bae1da34d 100644 --- a/tests/bunit.tests/Rendering/RenderedFragmentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedFragmentTest.cs @@ -72,7 +72,7 @@ public void Test009() cut.Instance.Counter.ShouldBe(1); - cut.Render((nameof(ToggleClickHandler.HandleClicks), false)); + cut.Render(ps => ps.Add(p => p.HandleClicks, false)); cut.Find("#btn").Click(); diff --git a/tests/bunit.tests/ShouldlyExtensions.cs b/tests/bunit.tests/ShouldlyExtensions.cs index 980b4707e..e25c463ce 100644 --- a/tests/bunit.tests/ShouldlyExtensions.cs +++ b/tests/bunit.tests/ShouldlyExtensions.cs @@ -1,6 +1,6 @@ namespace Bunit; -public static class ShouldlyExtensions +internal static class ShouldlyExtensions { public static void ShouldSatisfyAllConditions(this TCondition actual, params Action[] conditions) { diff --git a/tests/bunit.tests/TestContextTest.cs b/tests/bunit.tests/TestContextTest.cs index 0363670b0..087602d3d 100644 --- a/tests/bunit.tests/TestContextTest.cs +++ b/tests/bunit.tests/TestContextTest.cs @@ -108,7 +108,7 @@ public void Test032() public void Test033() { RenderTree.Add>(ps => ps.Add(p => p.Value, "FOO")); - var cut = Render(("Dummy", null)); + var cut = Render(ps => ps.Add(p => p.Dummy, null!)); cut.Instance .Value diff --git a/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs index 3dfc0e8e6..8caa8ebc3 100644 --- a/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs +++ b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs @@ -10,7 +10,8 @@ private sealed class ComponentDouble : ComponentDoubleBase>>((attrName, attrValue)); + var cut = Render>>(ps => ps + .AddUnmatched(attrName, attrValue)); cut.Instance.Parameters[attrName].ShouldBe(attrValue); } diff --git a/tests/bunit.tests/TestDoubles/Components/StubTest.cs b/tests/bunit.tests/TestDoubles/Components/StubTest.cs index 3208fe99f..b26296fa9 100644 --- a/tests/bunit.tests/TestDoubles/Components/StubTest.cs +++ b/tests/bunit.tests/TestDoubles/Components/StubTest.cs @@ -14,9 +14,9 @@ public void Test001() [AutoData] public void Test002(string header, string attrValue) { - var cut = Render>( - (nameof(Simple1.Header), header), - (nameof(Simple1.AttrValue), attrValue)); + var cut = Render>(ps => ps + .AddUnmatched(nameof(Simple1.Header), header) + .AddUnmatched(nameof(Simple1.AttrValue), attrValue)); cut.Instance .Parameters From 4d859bd797e6b5d21328ea406135d7479afcf513 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Mon, 4 Mar 2024 20:53:48 +0100 Subject: [PATCH 018/100] refactor: Remove net5 files and moved them to their main content --- .../BunitJSInteropSetupExtensions.cs | 126 ++++++++++++ .../BunitJSInteropSetupExtensions.net5.cs | 133 ------------- ...Runtime.net5.cs => BunitJSRuntime.net8.cs} | 0 .../MarkupMatchesAssertExtensionsTest.cs | 8 + .../MarkupMatchesAssertExtensionsTest.net5.cs | 12 -- .../JSInterop/BunitJSInteropTest.cs | 182 +++++++++++++++++ .../JSInterop/BunitJSInteropTest.net5.cs | 186 ------------------ ...RuntimeUnhandledInvocationExceptionTest.cs | 16 ++ ...meUnhandledInvocationExceptionTest.net5.cs | 20 -- .../Rendering/Internal/HtmlizerTests.cs | 18 +- .../Rendering/Internal/HtmlizerTests.net5.cs | 14 -- 11 files changed, 345 insertions(+), 370 deletions(-) delete mode 100644 src/bunit/JSInterop/BunitJSInteropSetupExtensions.net5.cs rename src/bunit/JSInterop/Implementation/{BunitJSRuntime.net5.cs => BunitJSRuntime.net8.cs} (100%) delete mode 100644 tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs delete mode 100644 tests/bunit.tests/JSInterop/BunitJSInteropTest.net5.cs delete mode 100644 tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs delete mode 100644 tests/bunit.tests/Rendering/Internal/HtmlizerTests.net5.cs diff --git a/src/bunit/JSInterop/BunitJSInteropSetupExtensions.cs b/src/bunit/JSInterop/BunitJSInteropSetupExtensions.cs index 7cc5059f6..a0eb7b219 100644 --- a/src/bunit/JSInterop/BunitJSInteropSetupExtensions.cs +++ b/src/bunit/JSInterop/BunitJSInteropSetupExtensions.cs @@ -1,3 +1,5 @@ +using Bunit.JSInterop.InvocationHandlers.Implementation; + namespace Bunit; ///

    @@ -5,6 +7,8 @@ namespace Bunit; /// public static partial class BunitJSInteropSetupExtensions { + private const string DefaultImportIdentifier = "import"; + /// /// Configure a JSInterop invocation handler for an InvokeAsync<TResult> call with arguments /// passing the test. @@ -146,6 +150,128 @@ public static JSRuntimeInvocationHandler SetupVoid(this BunitJSInterop jsInterop return jsInterop.TryGetHandlerFor(invocation, x => x.IsVoidResultHandler) as JSRuntimeInvocationHandler; } + /// + /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>() call whose input parameters is matched by the provided + /// . + /// + /// + /// The returned can be used to setup handlers for + /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either + /// or Setup calls. + /// + /// The JSInterop to setup the handler for. + /// The matcher to use to match 's with. + /// Set to true if the created handler is a catch all handler, that should only be used if there are no other non-catch all handlers available. + /// Thrown when is null. + /// Thrown when is null. + /// A . + public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, InvocationMatcher invocationMatcher, bool isCatchAllHandler = false) + { + ArgumentNullException.ThrowIfNull(jsInterop); + ArgumentNullException.ThrowIfNull(invocationMatcher); + + var result = new JSObjectReferenceInvocationHandler(jsInterop, invocationMatcher, isCatchAllHandler); + jsInterop.AddInvocationHandler(result); + return result.JSInterop; + } + + /// + /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>() call whose input parameters is matched by the provided + /// and the . + /// + /// + /// The returned can be used to setup handlers for + /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either + /// or Setup calls. + /// + /// The JSInterop to setup the handler for. + /// The identifier to setup a response for. + /// The matcher to use to match 's with. + /// Thrown when is null. + /// Thrown when is null. + /// A . + public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, string identifier, InvocationMatcher invocationMatcher) + => SetupModule(jsInterop, inv => identifier.Equals(inv.Identifier, StringComparison.Ordinal) && invocationMatcher(inv)); + + /// + /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>("import", ) + /// call. + /// + /// + /// The returned can be used to setup handlers for + /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either + /// or Setup calls. + /// + /// The JSInterop to setup the handler for. + /// The name of the JavaScript module to handle invocations for. + /// Thrown when is null. + /// Thrown when is null or whitespace. + /// A . + public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, string moduleName) + { + if (string.IsNullOrWhiteSpace(moduleName)) + throw new ArgumentException($"'{nameof(moduleName)}' cannot be null or whitespace.", nameof(moduleName)); + + return SetupModule( + jsInterop, + DefaultImportIdentifier, + invocation => invocation.Arguments?[0] is string requestedModuleName + && requestedModuleName.Equals(moduleName, StringComparison.Ordinal)); + } + + /// + /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>(, ) + /// call. + /// + /// + /// The returned can be used to setup handlers for + /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either + /// or Setup calls. + /// + /// The JSInterop to setup the handler for. + /// The identifier to setup a response for. + /// The arguments that an invocation to should match. Use Array.Empty<object?>() for none. + /// Thrown when is null. + /// Thrown when is null or whitespace. + /// A . + public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, string identifier, object?[] arguments) + => SetupModule(jsInterop, identifier, invocation => invocation.Arguments.SequenceEqual(arguments ?? Array.Empty())); + + /// + /// Configure a catch all JSObjectReferenceInvocationHandler invocation handler for any module load and invocations + /// on those modules. + /// + /// + /// The returned can be used to setup handlers for + /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either + /// or Setup calls. + /// + /// The JSInterop to setup the handler for. + /// Thrown when is null. + /// A . + public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop) + => SetupModule(jsInterop, _ => true, isCatchAllHandler: true); + + /// + /// Looks through the registered handlers and returns the latest registered that can handle + /// the provided and , and that + /// will return . + /// + /// The JSInterop to setup the handler for. + /// The identifier the handler should match with. + /// The arguments that an invocation to should match. + /// A or null if no one is found. + public static BunitJSModuleInterop? TryGetModuleJSInterop(this BunitJSInterop jsInterop, string identifier, params object?[]? arguments) + { + ArgumentNullException.ThrowIfNull(jsInterop); + + var invocation = new JSRuntimeInvocation(identifier, default, arguments, typeof(IJSObjectReference), "InvokeAsync"); + + var handler = jsInterop.TryGetHandlerFor(invocation) as JSObjectReferenceInvocationHandler; + + return handler?.JSInterop; + } + private static void EnsureResultNotIJSObjectReference() { const string UseSetupModuleErrorMessage = "Use one of the SetupModule() methods instead to set up an invocation handler that returns an IJSObjectReference."; diff --git a/src/bunit/JSInterop/BunitJSInteropSetupExtensions.net5.cs b/src/bunit/JSInterop/BunitJSInteropSetupExtensions.net5.cs deleted file mode 100644 index ebf393656..000000000 --- a/src/bunit/JSInterop/BunitJSInteropSetupExtensions.net5.cs +++ /dev/null @@ -1,133 +0,0 @@ -using Bunit.JSInterop.InvocationHandlers.Implementation; - -namespace Bunit; - -/// -/// Helper methods for creating invocation handlers and adding the to a . -/// -public static partial class BunitJSInteropSetupExtensions -{ - private const string DefaultImportIdentifier = "import"; - - /// - /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>() call whose input parameters is matched by the provided - /// . - /// - /// - /// The returned can be used to setup handlers for - /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either - /// or Setup calls. - /// - /// The JSInterop to setup the handler for. - /// The matcher to use to match 's with. - /// Set to true if the created handler is a catch all handler, that should only be used if there are no other non-catch all handlers available. - /// Thrown when is null. - /// Thrown when is null. - /// A . - public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, InvocationMatcher invocationMatcher, bool isCatchAllHandler = false) - { - ArgumentNullException.ThrowIfNull(jsInterop); - ArgumentNullException.ThrowIfNull(invocationMatcher); - - var result = new JSObjectReferenceInvocationHandler(jsInterop, invocationMatcher, isCatchAllHandler); - jsInterop.AddInvocationHandler(result); - return result.JSInterop; - } - - /// - /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>() call whose input parameters is matched by the provided - /// and the . - /// - /// - /// The returned can be used to setup handlers for - /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either - /// or Setup calls. - /// - /// The JSInterop to setup the handler for. - /// The identifier to setup a response for. - /// The matcher to use to match 's with. - /// Thrown when is null. - /// Thrown when is null. - /// A . - public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, string identifier, InvocationMatcher invocationMatcher) - => SetupModule(jsInterop, inv => identifier.Equals(inv.Identifier, StringComparison.Ordinal) && invocationMatcher(inv)); - - /// - /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>("import", ) - /// call. - /// - /// - /// The returned can be used to setup handlers for - /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either - /// or Setup calls. - /// - /// The JSInterop to setup the handler for. - /// The name of the JavaScript module to handle invocations for. - /// Thrown when is null. - /// Thrown when is null or whitespace. - /// A . - public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, string moduleName) - { - if (string.IsNullOrWhiteSpace(moduleName)) - throw new ArgumentException($"'{nameof(moduleName)}' cannot be null or whitespace.", nameof(moduleName)); - - return SetupModule( - jsInterop, - DefaultImportIdentifier, - invocation => invocation.Arguments?[0] is string requestedModuleName - && requestedModuleName.Equals(moduleName, StringComparison.Ordinal)); - } - - /// - /// Setup a handler for a IJSRuntime.InvokeAsync<IJSObjectReference>(, ) - /// call. - /// - /// - /// The returned can be used to setup handlers for - /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either - /// or Setup calls. - /// - /// The JSInterop to setup the handler for. - /// The identifier to setup a response for. - /// The arguments that an invocation to should match. Use Array.Empty<object?>() for none. - /// Thrown when is null. - /// Thrown when is null or whitespace. - /// A . - public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop, string identifier, object?[] arguments) - => SetupModule(jsInterop, identifier, invocation => invocation.Arguments.SequenceEqual(arguments ?? Array.Empty())); - - /// - /// Configure a catch all JSObjectReferenceInvocationHandler invocation handler for any module load and invocations - /// on those modules. - /// - /// - /// The returned can be used to setup handlers for - /// InvokeAsync<TValue>(string, object?[]?)" calls to the module, using either - /// or Setup calls. - /// - /// The JSInterop to setup the handler for. - /// Thrown when is null. - /// A . - public static BunitJSModuleInterop SetupModule(this BunitJSInterop jsInterop) - => SetupModule(jsInterop, _ => true, isCatchAllHandler: true); - - /// - /// Looks through the registered handlers and returns the latest registered that can handle - /// the provided and , and that - /// will return . - /// - /// The JSInterop to setup the handler for. - /// The identifier the handler should match with. - /// The arguments that an invocation to should match. - /// A or null if no one is found. - public static BunitJSModuleInterop? TryGetModuleJSInterop(this BunitJSInterop jsInterop, string identifier, params object?[]? arguments) - { - ArgumentNullException.ThrowIfNull(jsInterop); - - var invocation = new JSRuntimeInvocation(identifier, default, arguments, typeof(IJSObjectReference), "InvokeAsync"); - - var handler = jsInterop.TryGetHandlerFor(invocation) as JSObjectReferenceInvocationHandler; - - return handler?.JSInterop; - } -} diff --git a/src/bunit/JSInterop/Implementation/BunitJSRuntime.net5.cs b/src/bunit/JSInterop/Implementation/BunitJSRuntime.net8.cs similarity index 100% rename from src/bunit/JSInterop/Implementation/BunitJSRuntime.net5.cs rename to src/bunit/JSInterop/Implementation/BunitJSRuntime.net8.cs diff --git a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs index 336a7743d..db305bafb 100644 --- a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs +++ b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs @@ -151,4 +151,12 @@ public void Test016() cut.MarkupMatches(expectedMarkup); } + + [Fact(DisplayName = "MarkupMatches correctly ignores scoped CSS attributes")] + public void Test_net5_001() + { + var cut = Render(); + + cut.MarkupMatches("

    Hello Pink World!

    "); + } } diff --git a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs deleted file mode 100644 index 969805618..000000000 --- a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.net5.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Bunit.Asserting; - -public partial class MarkupMatchesAssertExtensionsTest : TestContext -{ - [Fact(DisplayName = "MarkupMatches correctly ignores scoped CSS attributes")] - public void Test_net5_001() - { - var cut = Render(); - - cut.MarkupMatches("

    Hello Pink World!

    "); - } -} diff --git a/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs index 7f53d5a9b..0a3826363 100644 --- a/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJSInteropTest.cs @@ -504,4 +504,186 @@ 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 } diff --git a/tests/bunit.tests/JSInterop/BunitJSInteropTest.net5.cs b/tests/bunit.tests/JSInterop/BunitJSInteropTest.net5.cs deleted file mode 100644 index 3262c6723..000000000 --- a/tests/bunit.tests/JSInterop/BunitJSInteropTest.net5.cs +++ /dev/null @@ -1,186 +0,0 @@ -#if !NET9_0_OR_GREATER -#pragma warning disable CS0618 // This method is obsolete. -namespace Bunit.JSInterop; - -public partial class BunitJSInteropTest -{ - [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 \ No newline at end of file diff --git a/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs index 4290db952..e1c5a4ae9 100644 --- a/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs +++ b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs @@ -292,6 +292,22 @@ public void Test035(string identifier) Assert.Equal(expectedErrorMessage, sut.Message); } + + [Theory(DisplayName = "Message prints correctly when trying to import an unconfigured module")] + [AutoData] + public void Test036(string moduleName) + { + var identifier = "import"; + var returnType = typeof(IJSObjectReference); + var invocationMethodName = "InvokeAsync"; + var expectedErrorMessage = CreateExpectedErrorMessage( + $"{CodeIdent}{invocationMethodName}<{returnType.Name}>(\"{identifier}\", \"{moduleName}\")", + $"{CodeIdent}SetupModule(\"{moduleName}\")"); + + var sut = new JSRuntimeUnhandledInvocationException(new JSRuntimeInvocation(identifier, new object?[] { moduleName }, returnType, invocationMethodName)); + + Assert.Equal(expectedErrorMessage, sut.Message); + } public class Dummy1 { } public class Dummy2 { } diff --git a/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs deleted file mode 100644 index a281ba6ea..000000000 --- a/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.net5.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace Bunit.JSInterop; - -public partial class JSRuntimeUnhandledInvocationExceptionTest -{ - [Theory(DisplayName = "Message prints correctly when trying to import an unconfigured module")] - [AutoData] - public void Test036(string moduleName) - { - var identifier = "import"; - var returnType = typeof(IJSObjectReference); - var invocationMethodName = "InvokeAsync"; - var expectedErrorMessage = CreateExpectedErrorMessage( - $"{CodeIdent}{invocationMethodName}<{returnType.Name}>(\"{identifier}\", \"{moduleName}\")", - $"{CodeIdent}SetupModule(\"{moduleName}\")"); - - var sut = new JSRuntimeUnhandledInvocationException(new JSRuntimeInvocation(identifier, new object?[] { moduleName }, returnType, invocationMethodName)); - - Assert.Equal(expectedErrorMessage, sut.Message); - } -} diff --git a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs index 0ef853158..f9891fde9 100644 --- a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs +++ b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs @@ -39,12 +39,11 @@ public void Test003() cut.Find("button").HasAttribute("blazor:elementreference").ShouldBeTrue(); } - -#if NET8_0_OR_GREATER + [Fact(DisplayName = "Htmlizer ignores NamedEvents")] public void Test004() { - var cut = RenderComponent(); + var cut = Render(); cut.MarkupMatches("""
    @@ -52,8 +51,17 @@ public void Test004()
    """); } -#endif - + + [Theory(DisplayName = "IsBlazorAttribute correctly identifies Blazor attributes")] + [InlineData("b-twl12ishk1=\"\"")] + [InlineData("blazor:onclick=\"1\"")] + [InlineData("blazor:__internal_stopPropagation_onclick=\"\"")] + [InlineData("blazor:__internal_preventDefault_onclick=\"\"")] + public void TestNET5_001(string blazorAttribute) + { + Htmlizer.IsBlazorAttribute(blazorAttribute).ShouldBeTrue(); + } + private sealed class Htmlizer01Component : ComponentBase { public ElementReference ButtomElmRef { get; set; } diff --git a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.net5.cs b/tests/bunit.tests/Rendering/Internal/HtmlizerTests.net5.cs deleted file mode 100644 index a2ef4e592..000000000 --- a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.net5.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Bunit.Rendering.Internal; - -public partial class HtmlizerTests : TestContext -{ - [Theory(DisplayName = "IsBlazorAttribute correctly identifies Blazor attributes")] - [InlineData("b-twl12ishk1=\"\"")] - [InlineData("blazor:onclick=\"1\"")] - [InlineData("blazor:__internal_stopPropagation_onclick=\"\"")] - [InlineData("blazor:__internal_preventDefault_onclick=\"\"")] - public void TestNET5_001(string blazorAttribute) - { - Htmlizer.IsBlazorAttribute(blazorAttribute).ShouldBeTrue(); - } -} From 104686d5ec742129b291b4e0e31ae504bc78161b Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Wed, 6 Mar 2024 21:38:32 +0100 Subject: [PATCH 019/100] feat: Add IAsyncDiposable for TestContext --- MIGRATION.md | 4 +++ src/bunit/TestContext.cs | 50 +++++++++++++++++++--------- tests/bunit.tests/TestContextTest.cs | 12 +++---- 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/MIGRATION.md b/MIGRATION.md index 4fbde291a..bf35ce11e 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -49,3 +49,7 @@ To make the API more consistent, `RenderComponent` and `SetParametersAndRender` ## Removal of `ComponentParameter` and method using them Using `ComponentParameter` and factory methods to create them is not recommend in V1 and have now been removed in V2. Instead, use the strongly typed builder pattern that enables you to pass parameters to components you render. + +## `TestContext` implements `IDisposable` and `IAsyncDisposable` +The `TestContext` now implements `IDisposable` and `IAsyncDisposable`. In version 1.x, `TestContext` only implemented `IDisposable` and cleaned up asynchronous objects in the synchronous `Dispose` method. This is no longer the case, and asynchronous objects are now cleaned up in the `DisposeAsync` method. +If you register services into the container that implement `IAsyncDisposable` make sure that the test framework calls the right method. diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 59daeeeec..693b7d591 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -7,7 +7,7 @@ namespace Bunit; /// /// A test context is a factory that makes it possible to create components under tests. /// -public partial class TestContext : IDisposable +public partial class TestContext : IDisposable, IAsyncDisposable { private bool disposed; private BunitRenderer? bunitRenderer; @@ -70,17 +70,46 @@ public void Dispose() GC.SuppressFinalize(this); } + /// + public async ValueTask DisposeAsync() + { + await DisposeAsyncCore(); + + Dispose(disposing: false); + GC.SuppressFinalize(this); + } + + /// + /// Disposes of the test context resources that are asynchronous, in particular it disposes the + /// service provider.s + /// + protected virtual async ValueTask DisposeAsyncCore() + { + if (disposed) + return; + + disposed = true; + + // Ensure the renderer is disposed before all others, + // otherwise a render cycle may be ongoing and try to access + // the service provider to perform operations. + if (bunitRenderer is not null) + { + await bunitRenderer.DisposeAsync(); + } + + await Services.DisposeAsync(); + } + /// /// Disposes of the test context resources, in particular it disposes the - /// service provider. Any async services registered with the service provider will disposed first, - /// but their disposal will not be awaited.. + /// service provider. /// /// /// The disposing parameter should be false when called from a finalizer, and true when called from the /// method. In other words, it is true when deterministically called and false when non-deterministically called. /// /// Set to true if called from , false if called from a finalizer.f. - [SuppressMessage("Reliability", "CA2012:Use ValueTasks correctly", Justification = "Explicitly ignoring DisposeAsync to avoid breaking changes to API surface.")] protected virtual void Dispose(bool disposing) { if (disposed || !disposing) @@ -91,18 +120,7 @@ protected virtual void Dispose(bool disposing) // Ensure the renderer is disposed before all others, // otherwise a render cycle may be ongoing and try to access // the service provider to perform operations. - if (bunitRenderer is IDisposable renderer) - { - renderer.Dispose(); - } - - // Ignore the async task as GetAwaiter().GetResult() can cause deadlock - // and implementing IAsyncDisposable in TestContext will be a breaking change. - // - // NOTE: This has to be called before Services.Dispose(). - // If there are IAsyncDisposable services registered, calling Dispose first - // causes the service provider to throw an exception. - _ = Services.DisposeAsync(); + bunitRenderer?.Dispose(); // The service provider should dispose of any // disposable object it has created, when it is disposed. diff --git a/tests/bunit.tests/TestContextTest.cs b/tests/bunit.tests/TestContextTest.cs index 087602d3d..dc1dc39d9 100644 --- a/tests/bunit.tests/TestContextTest.cs +++ b/tests/bunit.tests/TestContextTest.cs @@ -207,10 +207,10 @@ public void Test203() } [Fact(DisplayName = "Can correctly resolve and dispose of scoped disposable service")] - public void Net5Test001() + public async Task Net5Test001() { AsyncDisposableService asyncDisposable; - using (var sut = new TestContext()) + await using (var sut = new TestContext()) { sut.Services.AddScoped(); asyncDisposable = sut.Services.GetService(); @@ -219,10 +219,10 @@ public void Net5Test001() } [Fact(DisplayName = "Can correctly resolve and dispose of transient disposable service")] - public void Net5Test002() + public async Task Net5Test002() { AsyncDisposableService asyncDisposable; - using (var sut = new TestContext()) + await using (var sut = new TestContext()) { sut.Services.AddTransient(); asyncDisposable = sut.Services.GetService(); @@ -231,10 +231,10 @@ public void Net5Test002() } [Fact(DisplayName = "Can correctly resolve and dispose of singleton disposable service")] - public void Net5Test003() + public async Task Net5Test003() { AsyncDisposableService asyncDisposable; - using (var sut = new TestContext()) + await using (var sut = new TestContext()) { sut.Services.AddSingleton(); asyncDisposable = sut.Services.GetService(); From 3042be55eaa0543818d07469d649ae53f01f0dea Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 16:08:08 +0100 Subject: [PATCH 020/100] refactor: Rename TestContext to BunitContext --- MIGRATION.md | 33 ++- docs/samples/tests/mstest/BunitTestContext.cs | 13 -- .../mstest/HelloWorldExplicitContextTest.cs | 2 +- .../tests/mstest/HelloWorldRazorTest.razor | 2 +- docs/samples/tests/mstest/HelloWorldTest.cs | 2 +- docs/samples/tests/nunit/BunitTestContext.cs | 13 -- .../nunit/HelloWorldExplicitContextTest.cs | 2 +- .../nunit/HelloWorldInstancePerTestCase.cs | 2 +- .../HelloWorldRazorInstancePerTestCase.razor | 2 +- .../tests/nunit/HelloWorldRazorTest.razor | 2 +- docs/samples/tests/nunit/HelloWorldTest.cs | 2 +- .../tests/razor/CascadingParams1Test.razor | 2 +- .../tests/razor/CascadingParams2Test.razor | 2 +- .../tests/razor/CascadingParams3Test.razor | 2 +- .../tests/razor/ChildContentParams1Test.razor | 2 +- .../tests/razor/ChildContentParams2Test.razor | 2 +- .../tests/razor/ChildContentParams3Test.razor | 2 +- .../tests/razor/ChildContentParams4Test.razor | 2 +- docs/samples/tests/razor/ClickMeTest.razor | 2 +- docs/samples/tests/razor/CounterTest.razor | 2 +- .../tests/razor/EventCallbackParamsTest.razor | 2 +- .../tests/razor/NestedComponentTest.razor | 2 +- .../razor/NonBlazorTypesParamsTest.razor | 2 +- .../razor/RenderFragmentParams1Test.razor | 2 +- .../razor/RenderFragmentParams2Test.razor | 2 +- .../razor/RenderFragmentParams3Test.razor | 2 +- .../razor/RenderFragmentParams4Test.razor | 2 +- .../tests/razor/TwoWayBindingTest.razor | 2 +- .../tests/razor/UnmatchedParamsTest.razor | 2 +- docs/samples/tests/xunit/AsyncDataTest.cs | 2 +- .../tests/xunit/CascadingParams1Test.cs | 2 +- .../tests/xunit/CascadingParams2Test.cs | 2 +- .../tests/xunit/CascadingParams3Test.cs | 2 +- .../tests/xunit/ChildContentParams1Test.cs | 2 +- .../tests/xunit/ChildContentParams2Test.cs | 2 +- .../tests/xunit/ChildContentParams3Test.cs | 2 +- .../tests/xunit/ChildContentParams4Test.cs | 2 +- docs/samples/tests/xunit/ClickMeTest.cs | 2 +- .../xunit/ComponentFactoryExampleTest.cs | 2 +- docs/samples/tests/xunit/CounterTest.cs | 2 +- .../samples/tests/xunit/CounterTestWithCtx.cs | 2 +- .../xunit/CounterWithFancyParagraphTest.cs | 2 +- .../CustomServiceProviderFactoryUsage.cs | 14 +- .../tests/xunit/DisposeComponentsTest.cs | 2 +- .../tests/xunit/EventCallbackParamsTest.cs | 2 +- .../xunit/FallBackServiceProviderUsage.cs | 2 +- .../HelloWorldExplicitContextRazorTest.razor | 2 +- .../xunit/HelloWorldExplicitContextTest.cs | 2 +- .../HelloWorldImplicitContextRazorTest.razor | 2 +- .../tests/xunit/HelloWorldRazorTest.razor | 2 +- docs/samples/tests/xunit/HelloWorldTest.cs | 2 +- .../tests/xunit/InjectAuthServiceTest.cs | 2 +- .../tests/xunit/NestedComponentTest.cs | 2 +- .../tests/xunit/NonBlazorTypesParamsTest.cs | 2 +- docs/samples/tests/xunit/ReRenderTest.cs | 2 +- .../tests/xunit/RenderFragmentParams1Test.cs | 2 +- .../tests/xunit/RenderFragmentParams2Test.cs | 2 +- .../tests/xunit/RenderFragmentParams3Test.cs | 2 +- .../tests/xunit/RenderFragmentParams4Test.cs | 2 +- docs/samples/tests/xunit/RenderTreeTest.cs | 2 +- docs/samples/tests/xunit/SemanticHtmlTest.cs | 2 +- .../tests/xunit/TemplateParams1Test.cs | 2 +- .../tests/xunit/TemplateParams2Test.cs | 2 +- docs/samples/tests/xunit/TwoWayBindingTest.cs | 2 +- .../tests/xunit/UnmatchedParamsTest.cs | 2 +- docs/samples/tests/xunit/UserInfoTest.cs | 2 +- docs/samples/tests/xunit/UserRightsTest.cs | 2 +- .../tests/xunit/VerifyMarkupExamples.cs | 2 +- .../tests/xunit/WeatherForecastsTest.cs | 2 +- docs/site/docs/extensions/bunit-generators.md | 2 +- .../docs/getting-started/writing-tests.md | 60 ++---- .../docs/interaction/dispose-components.md | 4 +- docs/site/docs/interaction/trigger-renders.md | 6 +- docs/site/docs/misc-test-tips.md | 2 +- .../passing-parameters-to-components.md | 48 ++--- .../docs/providing-input/root-render-tree.md | 2 +- .../substituting-components.md | 2 +- docs/site/docs/test-doubles/auth.md | 4 +- .../fake-webassemblyhostenvironment.md | 2 +- .../docs/test-doubles/mocking-localizer.md | 2 +- .../docs/test-doubles/navigation-manager.md | 2 +- .../test-doubles/persistentcomponentstate.md | 2 +- .../verification/verify-component-state.md | 4 +- src/bunit.generators/README.md | 2 +- .../template/BunitTestContext.cs | 29 --- .../template/CounterCSharpTests.cs | 6 +- .../template/CounterRazorTests.razor | 6 +- .../MarkupMatchesAssertExtensions.cs | 6 +- src/bunit/BunitContext.cs | 190 ++++++++++++++++++ .../InstanceComponentFactory{TComponent}.cs | 2 +- .../TriggerEventDispatchExtensions.cs | 2 +- .../Internal/AngleSharpExtensions.cs | 16 +- .../RenderedComponentRenderExtensions.cs | 2 +- .../Extensions/RenderedFragmentExtensions.cs | 4 +- .../RenderedFragmentInvokeAsyncExtensions.cs | 8 +- .../Extensions/TestContextRenderExtensions.cs | 30 +-- .../TestServiceProviderExtensions.cs | 8 +- .../WaitForHelpers/WaitForHelper.cs | 4 +- .../JSRuntimeUnhandledInvocationException.cs | 2 +- .../Rendering/BunitComponentActivator.cs | 2 +- src/bunit/Rendering/BunitHtmlParser.cs | 6 +- src/bunit/TestContext.cs | 189 +---------------- src/bunit/TestContextWrapper.cs | 81 -------- .../BunitAuthorizationExtensions.cs | 2 +- .../MissingBunitAuthorizationException.cs | 4 +- .../BunitNavigationManager.cs | 8 +- .../BunitPersistentComponentState.cs | 8 +- .../TestContextExtensions.cs | 4 +- src/bunit/TestServiceProvider.cs | 2 +- ...atorTests.cs => AddStubGeneratorBunits.cs} | 2 +- ....cs => CompareToDiffingExtensionsBunit.cs} | 2 +- ... => MarkupMatchesAssertExtensionsBunit.cs} | 2 +- .../Asserting/MarkupMatchesTests.razor | 2 +- ...ringTest.cs => ComponentRenderingBunit.cs} | 8 +- ...estContextTest.cs => BunitContextBunit.cs} | 12 +- ...cs => ConditionalComponentFactoryBunit.cs} | 2 +- ...est.cs => GenericComponentFactoryBunit.cs} | 2 +- ...st.cs => InstanceComponentFactoryBunit.cs} | 2 +- ...ryTest.cs => StubComponentFactoryBunit.cs} | 2 +- ...t.cs => TypeBasedComponentFactoryBunit.cs} | 2 +- ...ponentParameterCollectionBuilderBunits.cs} | 2 +- ...entParameterCollectionBuilderBunits.razor} | 2 +- ...s => ComponentParameterCollectionBunit.cs} | 2 +- ... ClipboardEventDispatchExtensionsBunit.cs} | 4 +- ...sElementEventDispatcherExtensionsBunit.cs} | 2 +- ...cs => DragEventDispatchExtensionsBunit.cs} | 4 +- ...est.cs => EventDispatchExtensionsBunit.cs} | 4 +- ...s => FocusEventDispatchExtensionsBunit.cs} | 4 +- ...=> GeneralEventDispatchExtensionsBunit.cs} | 6 +- ...s => InputEventDispatchExtensionsBunit.cs} | 4 +- ...> KeyboardEventDispatchExtensionsBunit.cs} | 4 +- ...s => MediaEventDispatchExtensionsBunit.cs} | 4 +- ...s => MouseEventDispatchExtensionsBunit.cs} | 4 +- ...=> PointerEventDispatchExtensionsBunit.cs} | 4 +- ...> ProgressEventDispatchExtensionsBunit.cs} | 4 +- ...s => TouchEventDispatchExtensionsBunit.cs} | 4 +- ...s => WheelEventDispatchExtensionsBunit.cs} | 4 +- .../{InputFileTests.cs => InputFileBunits.cs} | 2 +- ....cs => RefreshableQueryCollectionBunit.cs} | 2 +- ...st.cs => RefreshingWrappedElementBunit.cs} | 2 +- ...RenderedComponentRenderExtensionsBunit.cs} | 2 +- ...tForElementsHelperExtensions.Async.Test.cs | 6 +- ...ntWaitForElementsHelperExtensionsBunit.cs} | 6 +- ...edFragmentWaitForHelperExtensionsBunit.cs} | 4 +- ...Test.cs => BunitJsObjectReferenceBunit.cs} | 2 +- ...cs => FocusAsyncInvocationHandlerBunit.cs} | 2 +- ...Test.cs => FocusOnNavigateHandlerBunit.cs} | 2 +- ...tualizeJsRuntimeInvocationHandlerBunit.cs} | 2 +- ...RuntimeUnhandledInvocationExceptionTest.cs | 4 +- ...est.cs => BunitComponentActivatorBunit.cs} | 2 +- ...endererTests.cs => BunitRendererBunits.cs} | 4 +- .../{HtmlizerTests.cs => HtmlizerBunits.cs} | 2 +- ...onentTest.cs => RenderedComponentBunit.cs} | 2 +- ...agmentTest.cs => RenderedFragmentBunit.cs} | 4 +- ...nderTreeTest.cs => RootRenderTreeBunit.cs} | 2 +- ...orizationTest.cs => AuthorizationBunit.cs} | 6 +- .../BunitAuthorizationContextBunit.cs | 2 +- .../BunitAuthorizationServiceTest.cs | 4 +- ...> BunitSignOutSessionStateManagerBunit.cs} | 2 +- ...> BunitWebAssemblyHostEnvironmentBunit.cs} | 2 +- ...aseTest.cs => ComponentDoubleBaseBunit.cs} | 2 +- .../Components/{StubTest.cs => StubBunit.cs} | 2 +- .../BunitNavigationInterceptionTest.cs | 2 +- ...Test.cs => BunitNavigationManagerBunit.cs} | 4 +- ... => BunitPersistentComponentStateBunit.cs} | 4 +- tests/bunit.tests/TestServiceProviderTest.cs | 8 +- 166 files changed, 509 insertions(+), 649 deletions(-) delete mode 100644 docs/samples/tests/mstest/BunitTestContext.cs delete mode 100644 docs/samples/tests/nunit/BunitTestContext.cs delete mode 100644 src/bunit.template/template/BunitTestContext.cs create mode 100644 src/bunit/BunitContext.cs delete mode 100644 src/bunit/TestContextWrapper.cs rename tests/bunit.generators.tests/Web.Stub/{AddStubGeneratorTests.cs => AddStubGeneratorBunits.cs} (97%) rename tests/bunit.tests/Asserting/{CompareToDiffingExtensionsTest.cs => CompareToDiffingExtensionsBunit.cs} (97%) rename tests/bunit.tests/Asserting/{MarkupMatchesAssertExtensionsTest.cs => MarkupMatchesAssertExtensionsBunit.cs} (99%) rename tests/bunit.tests/BlazorE2E/{ComponentRenderingTest.cs => ComponentRenderingBunit.cs} (99%) rename tests/bunit.tests/{TestContextTest.cs => BunitContextBunit.cs} (96%) rename tests/bunit.tests/ComponentFactories/{ConditionalComponentFactoryTest.cs => ConditionalComponentFactoryBunit.cs} (97%) rename tests/bunit.tests/ComponentFactories/{GenericComponentFactoryTest.cs => GenericComponentFactoryBunit.cs} (95%) rename tests/bunit.tests/ComponentFactories/{InstanceComponentFactoryTest.cs => InstanceComponentFactoryBunit.cs} (96%) rename tests/bunit.tests/ComponentFactories/{StubComponentFactoryTest.cs => StubComponentFactoryBunit.cs} (98%) rename tests/bunit.tests/ComponentFactories/{TypeBasedComponentFactoryTest.cs => TypeBasedComponentFactoryBunit.cs} (95%) rename tests/bunit.tests/{ComponentParameterCollectionBuilderTests.cs => ComponentParameterCollectionBuilderBunits.cs} (99%) rename tests/bunit.tests/{ComponentParameterCollectionBuilderTests.razor => ComponentParameterCollectionBuilderBunits.razor} (97%) rename tests/bunit.tests/{ComponentParameterCollectionTest.cs => ComponentParameterCollectionBunit.cs} (99%) rename tests/bunit.tests/EventDispatchExtensions/{ClipboardEventDispatchExtensionsTest.cs => ClipboardEventDispatchExtensionsBunit.cs} (67%) rename tests/bunit.tests/EventDispatchExtensions/{DetailsElementEventDispatcherExtensionsTest.cs => DetailsElementEventDispatcherExtensionsBunit.cs} (80%) rename tests/bunit.tests/EventDispatchExtensions/{DragEventDispatchExtensionsTest.cs => DragEventDispatchExtensionsBunit.cs} (77%) rename tests/bunit.tests/EventDispatchExtensions/{EventDispatchExtensionsTest.cs => EventDispatchExtensionsBunit.cs} (96%) rename tests/bunit.tests/EventDispatchExtensions/{FocusEventDispatchExtensionsTest.cs => FocusEventDispatchExtensionsBunit.cs} (68%) rename tests/bunit.tests/EventDispatchExtensions/{GeneralEventDispatchExtensionsTest.cs => GeneralEventDispatchExtensionsBunit.cs} (98%) rename tests/bunit.tests/EventDispatchExtensions/{InputEventDispatchExtensionsTest.cs => InputEventDispatchExtensionsBunit.cs} (98%) rename tests/bunit.tests/EventDispatchExtensions/{KeyboardEventDispatchExtensionsTest.cs => KeyboardEventDispatchExtensionsBunit.cs} (95%) rename tests/bunit.tests/EventDispatchExtensions/{MediaEventDispatchExtensionsTest.cs => MediaEventDispatchExtensionsBunit.cs} (65%) rename tests/bunit.tests/EventDispatchExtensions/{MouseEventDispatchExtensionsTest.cs => MouseEventDispatchExtensionsBunit.cs} (92%) rename tests/bunit.tests/EventDispatchExtensions/{PointerEventDispatchExtensionsTest.cs => PointerEventDispatchExtensionsBunit.cs} (80%) rename tests/bunit.tests/EventDispatchExtensions/{ProgressEventDispatchExtensionsTest.cs => ProgressEventDispatchExtensionsBunit.cs} (70%) rename tests/bunit.tests/EventDispatchExtensions/{TouchEventDispatchExtensionsTest.cs => TouchEventDispatchExtensionsBunit.cs} (76%) rename tests/bunit.tests/EventDispatchExtensions/{WheelEventDispatchExtensionsTest.cs => WheelEventDispatchExtensionsBunit.cs} (80%) rename tests/bunit.tests/Extensions/InputFile/{InputFileTests.cs => InputFileBunits.cs} (99%) rename tests/bunit.tests/Extensions/{RefreshableQueryCollectionTest.cs => RefreshableQueryCollectionBunit.cs} (96%) rename tests/bunit.tests/Extensions/{RefreshingWrappedElementTest.cs => RefreshingWrappedElementBunit.cs} (97%) rename tests/bunit.tests/Extensions/{RenderedComponentRenderExtensionsTest.cs => RenderedComponentRenderExtensionsBunit.cs} (84%) rename tests/bunit.tests/Extensions/WaitForHelpers/{RenderedFragmentWaitForElementsHelperExtensionsTest.cs => RenderedFragmentWaitForElementsHelperExtensionsBunit.cs} (93%) rename tests/bunit.tests/Extensions/WaitForHelpers/{RenderedFragmentWaitForHelperExtensionsTest.cs => RenderedFragmentWaitForHelperExtensionsBunit.cs} (96%) rename tests/bunit.tests/JSInterop/{BunitJSObjectReferenceTest.cs => BunitJsObjectReferenceBunit.cs} (99%) rename tests/bunit.tests/JSInterop/InvocationHandlers/{FocusAsyncInvocationHandlerTest.cs => FocusAsyncInvocationHandlerBunit.cs} (95%) rename tests/bunit.tests/JSInterop/InvocationHandlers/{FocusOnNavigateHandlerTest.cs => FocusOnNavigateHandlerBunit.cs} (96%) rename tests/bunit.tests/JSInterop/InvocationHandlers/{VirtualizeJSRuntimeInvocationHandlerTest.cs => VirtualizeJsRuntimeInvocationHandlerBunit.cs} (98%) rename tests/bunit.tests/Rendering/{BunitComponentActivatorTest.cs => BunitComponentActivatorBunit.cs} (96%) rename tests/bunit.tests/Rendering/{BunitRendererTests.cs => BunitRendererBunits.cs} (99%) rename tests/bunit.tests/Rendering/Internal/{HtmlizerTests.cs => HtmlizerBunits.cs} (98%) rename tests/bunit.tests/Rendering/{RenderedComponentTest.cs => RenderedComponentBunit.cs} (97%) rename tests/bunit.tests/Rendering/{RenderedFragmentTest.cs => RenderedFragmentBunit.cs} (97%) rename tests/bunit.tests/Rendering/{RootRenderTreeTest.cs => RootRenderTreeBunit.cs} (99%) rename tests/bunit.tests/TestDoubles/Authorization/{AuthorizationTest.cs => AuthorizationBunit.cs} (97%) rename tests/bunit.tests/TestDoubles/{BunitSignOutSessionStateManagerTest.cs => BunitSignOutSessionStateManagerBunit.cs} (91%) rename tests/bunit.tests/TestDoubles/{BunitWebAssemblyHostEnvironmentTest.cs => BunitWebAssemblyHostEnvironmentBunit.cs} (92%) rename tests/bunit.tests/TestDoubles/Components/{ComponentDoubleBaseTest.cs => ComponentDoubleBaseBunit.cs} (89%) rename tests/bunit.tests/TestDoubles/Components/{StubTest.cs => StubBunit.cs} (95%) rename tests/bunit.tests/TestDoubles/NavigationManager/{BunitNavigationManagerTest.cs => BunitNavigationManagerBunit.cs} (98%) rename tests/bunit.tests/TestDoubles/PersistentComponentState/{BunitPersistentComponentStateTest.cs => BunitPersistentComponentStateBunit.cs} (93%) diff --git a/MIGRATION.md b/MIGRATION.md index bf35ce11e..7a4a6ab88 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -39,10 +39,10 @@ The `WebTestRender` class has been merged into the `TestRender` class. If you us The `Fake` prefix has been replaced with `Bunit` in many test doubles. For example, `FakeNavigationManager` is now `BunitNavigationManager`. If you reference any of these types explicitly, you need to update your code. ### Renamed `AddTestAuthorization` to `AddAuthorization` -The `AddTestAuthorization` method on `TestContext` has been renamed to `AddAuthorization`. If you used `AddTestAuthorization`, you should replace it with `AddAuthorization`. +The `AddTestAuthorization` method on `BunitContext` has been renamed to `AddAuthorization`. If you used `AddTestAuthorization`, you should replace it with `AddAuthorization`. -## Merged `TestContext` and `TestContextBase` -The `TestContext` and `TestContextBase` classes have been merged into a single `TestContext` class. All references to `TestContextBase` should replace them with `TestContext` to migrate. +## Merged `BunitContext` and `BunitContextBase` +The `BunitContext` and `BunitContextBase` classes have been merged into a single `BunitContext` class. All references to `BunitContextBase` should replace them with `BunitContext` to migrate. ## Renamed all `RenderComponent` and `SetParametersAndRender` to `Render` To make the API more consistent, `RenderComponent` and `SetParametersAndRender` methods have been renamed to `Render`. @@ -50,6 +50,29 @@ To make the API more consistent, `RenderComponent` and `SetParametersAndRender` ## Removal of `ComponentParameter` and method using them Using `ComponentParameter` and factory methods to create them is not recommend in V1 and have now been removed in V2. Instead, use the strongly typed builder pattern that enables you to pass parameters to components you render. -## `TestContext` implements `IDisposable` and `IAsyncDisposable` -The `TestContext` now implements `IDisposable` and `IAsyncDisposable`. In version 1.x, `TestContext` only implemented `IDisposable` and cleaned up asynchronous objects in the synchronous `Dispose` method. This is no longer the case, and asynchronous objects are now cleaned up in the `DisposeAsync` method. +## `BunitContext` implements `IDisposable` and `IAsyncDisposable` +The `BunitContext` now implements `IDisposable` and `IAsyncDisposable`. In version 1.x, `BunitContext` only implemented `IDisposable` and cleaned up asynchronous objects in the synchronous `Dispose` method. This is no longer the case, and asynchronous objects are now cleaned up in the `DisposeAsync` method. If you register services into the container that implement `IAsyncDisposable` make sure that the test framework calls the right method. + +## `TestContext` was renamed to `BunitContext` +The `TestContext` class has been renamed to `BunitContext`. If you used `TestContext`, you should replace it with `BunitContext`. + +## `TestContextWrapper` was removed +The `TestContextWrapper` class has been removed. Either use lifecycle events of the testing framework (like `LifeCycle.InstancePerTestCase` in NUnit). +```csharp +[FixtureLifeCycle(LifeCycle.InstancePerTestCase)] +public class HelloWorldInstancePerTestCase : Bunit.TestContext +{ + [Test] + public void HelloWorldComponentRendersCorrectly() + { + // Act + var cut = RenderComponent(); + + // Assert + cut.MarkupMatches("

    Hello world from Blazor

    "); + } +} +``` + +Or use the `BunitContext` directly and manage the lifecycle yourself. diff --git a/docs/samples/tests/mstest/BunitTestContext.cs b/docs/samples/tests/mstest/BunitTestContext.cs deleted file mode 100644 index 2dad801cf..000000000 --- a/docs/samples/tests/mstest/BunitTestContext.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Bunit.Docs.Samples; - -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Bunit; - -public abstract class BunitTestContext : TestContextWrapper -{ - [TestInitialize] - public void Setup() => TestContext = new Bunit.TestContext(); - - [TestCleanup] - public void TearDown() => TestContext?.Dispose(); -} \ No newline at end of file diff --git a/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs b/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs index a4b7942af..e7f2aebab 100644 --- a/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs +++ b/docs/samples/tests/mstest/HelloWorldExplicitContextTest.cs @@ -10,7 +10,7 @@ public class HelloWorldExplicitContext public void HelloWorldComponentRendersCorrectly() { // Arrange - using var ctx = new Bunit.TestContext(); + using var ctx = new Bunit.BunitContext(); // Act var cut = ctx.Render(); diff --git a/docs/samples/tests/mstest/HelloWorldRazorTest.razor b/docs/samples/tests/mstest/HelloWorldRazorTest.razor index f821bd1ab..12b56f0ff 100644 --- a/docs/samples/tests/mstest/HelloWorldRazorTest.razor +++ b/docs/samples/tests/mstest/HelloWorldRazorTest.razor @@ -1,5 +1,5 @@ @attribute [TestClass] -@inherits BunitTestContext +@inherits BunitContext @code { [TestMethod] diff --git a/docs/samples/tests/mstest/HelloWorldTest.cs b/docs/samples/tests/mstest/HelloWorldTest.cs index a83afd638..f2f08e7d4 100644 --- a/docs/samples/tests/mstest/HelloWorldTest.cs +++ b/docs/samples/tests/mstest/HelloWorldTest.cs @@ -4,7 +4,7 @@ namespace Bunit.Docs.Samples; using Bunit; [TestClass] -public class HelloWorldTest : BunitTestContext +public class HelloWorldTest : BunitContext { [TestMethod] public void HelloWorldComponentRendersCorrectly() diff --git a/docs/samples/tests/nunit/BunitTestContext.cs b/docs/samples/tests/nunit/BunitTestContext.cs deleted file mode 100644 index 00dd5f7d0..000000000 --- a/docs/samples/tests/nunit/BunitTestContext.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Bunit.Docs.Samples; - -using Bunit; -using NUnit.Framework; - -public abstract class BunitTestContext : TestContextWrapper -{ - [SetUp] - public void Setup() => TestContext = new Bunit.TestContext(); - - [TearDown] - public void TearDown() => TestContext?.Dispose(); -} \ No newline at end of file diff --git a/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs b/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs index 6727db19d..fede764e6 100644 --- a/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs +++ b/docs/samples/tests/nunit/HelloWorldExplicitContextTest.cs @@ -9,7 +9,7 @@ public class HelloWorldExplicitContext public void HelloWorldComponentRendersCorrectly() { // Arrange - using var ctx = new Bunit.TestContext(); + using var ctx = new Bunit.BunitContext(); // Act var cut = ctx.Render(); diff --git a/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs b/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs index b5d7142be..562823627 100644 --- a/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs +++ b/docs/samples/tests/nunit/HelloWorldInstancePerTestCase.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; [FixtureLifeCycle(LifeCycle.InstancePerTestCase)] -public class HelloWorldInstancePerTestCase : Bunit.TestContext +public class HelloWorldInstancePerTestCase : Bunit.BunitContext { [Test] public void HelloWorldComponentRendersCorrectly() diff --git a/docs/samples/tests/nunit/HelloWorldRazorInstancePerTestCase.razor b/docs/samples/tests/nunit/HelloWorldRazorInstancePerTestCase.razor index 4685d907d..fec14a60d 100644 --- a/docs/samples/tests/nunit/HelloWorldRazorInstancePerTestCase.razor +++ b/docs/samples/tests/nunit/HelloWorldRazorInstancePerTestCase.razor @@ -1,5 +1,5 @@ @attribute [FixtureLifeCycle(LifeCycle.InstancePerTestCase)] -@inherits Bunit.TestContext +@inherits Bunit.BunitContext @code { [Test] diff --git a/docs/samples/tests/nunit/HelloWorldRazorTest.razor b/docs/samples/tests/nunit/HelloWorldRazorTest.razor index 6de4ac4f4..ac54446f1 100644 --- a/docs/samples/tests/nunit/HelloWorldRazorTest.razor +++ b/docs/samples/tests/nunit/HelloWorldRazorTest.razor @@ -1,4 +1,4 @@ -@inherits BunitTestContext +@inherits BunitContext @code { [Test] diff --git a/docs/samples/tests/nunit/HelloWorldTest.cs b/docs/samples/tests/nunit/HelloWorldTest.cs index cce56a764..74ce9aa4c 100644 --- a/docs/samples/tests/nunit/HelloWorldTest.cs +++ b/docs/samples/tests/nunit/HelloWorldTest.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; using Bunit; using NUnit.Framework; -public class HelloWorldTest : BunitTestContext +public class HelloWorldTest : BunitContext { [Test] public void HelloWorldComponentRendersCorrectly() diff --git a/docs/samples/tests/razor/CascadingParams1Test.razor b/docs/samples/tests/razor/CascadingParams1Test.razor index db67f0142..d3db4114d 100644 --- a/docs/samples/tests/razor/CascadingParams1Test.razor +++ b/docs/samples/tests/razor/CascadingParams1Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/CascadingParams2Test.razor b/docs/samples/tests/razor/CascadingParams2Test.razor index 3dc8d73d0..b4251f8b7 100644 --- a/docs/samples/tests/razor/CascadingParams2Test.razor +++ b/docs/samples/tests/razor/CascadingParams2Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/CascadingParams3Test.razor b/docs/samples/tests/razor/CascadingParams3Test.razor index fa0f03812..c66a95bd7 100644 --- a/docs/samples/tests/razor/CascadingParams3Test.razor +++ b/docs/samples/tests/razor/CascadingParams3Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/ChildContentParams1Test.razor b/docs/samples/tests/razor/ChildContentParams1Test.razor index 18ee564e4..069c24e84 100644 --- a/docs/samples/tests/razor/ChildContentParams1Test.razor +++ b/docs/samples/tests/razor/ChildContentParams1Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/ChildContentParams2Test.razor b/docs/samples/tests/razor/ChildContentParams2Test.razor index 7ff765e5c..b1f2184f2 100644 --- a/docs/samples/tests/razor/ChildContentParams2Test.razor +++ b/docs/samples/tests/razor/ChildContentParams2Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/ChildContentParams3Test.razor b/docs/samples/tests/razor/ChildContentParams3Test.razor index 9e1041bc8..c802e92ee 100644 --- a/docs/samples/tests/razor/ChildContentParams3Test.razor +++ b/docs/samples/tests/razor/ChildContentParams3Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/ChildContentParams4Test.razor b/docs/samples/tests/razor/ChildContentParams4Test.razor index fb9751d92..dc2ce5beb 100644 --- a/docs/samples/tests/razor/ChildContentParams4Test.razor +++ b/docs/samples/tests/razor/ChildContentParams4Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/ClickMeTest.razor b/docs/samples/tests/razor/ClickMeTest.razor index 940aa5595..0534006e6 100644 --- a/docs/samples/tests/razor/ClickMeTest.razor +++ b/docs/samples/tests/razor/ClickMeTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/CounterTest.razor b/docs/samples/tests/razor/CounterTest.razor index 3f2e471a0..2ccc845be 100644 --- a/docs/samples/tests/razor/CounterTest.razor +++ b/docs/samples/tests/razor/CounterTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { [Fact] public void CounterShouldIncrementWhenClicked() diff --git a/docs/samples/tests/razor/EventCallbackParamsTest.razor b/docs/samples/tests/razor/EventCallbackParamsTest.razor index 02482b6ef..872d7a603 100644 --- a/docs/samples/tests/razor/EventCallbackParamsTest.razor +++ b/docs/samples/tests/razor/EventCallbackParamsTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/NestedComponentTest.razor b/docs/samples/tests/razor/NestedComponentTest.razor index 470a1b06c..007d17d8a 100644 --- a/docs/samples/tests/razor/NestedComponentTest.razor +++ b/docs/samples/tests/razor/NestedComponentTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/NonBlazorTypesParamsTest.razor b/docs/samples/tests/razor/NonBlazorTypesParamsTest.razor index af4f64dd6..3f87d42e8 100644 --- a/docs/samples/tests/razor/NonBlazorTypesParamsTest.razor +++ b/docs/samples/tests/razor/NonBlazorTypesParamsTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/RenderFragmentParams1Test.razor b/docs/samples/tests/razor/RenderFragmentParams1Test.razor index 0ffb568ca..efb31ff44 100644 --- a/docs/samples/tests/razor/RenderFragmentParams1Test.razor +++ b/docs/samples/tests/razor/RenderFragmentParams1Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/RenderFragmentParams2Test.razor b/docs/samples/tests/razor/RenderFragmentParams2Test.razor index ceb160a91..9df4c598d 100644 --- a/docs/samples/tests/razor/RenderFragmentParams2Test.razor +++ b/docs/samples/tests/razor/RenderFragmentParams2Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/RenderFragmentParams3Test.razor b/docs/samples/tests/razor/RenderFragmentParams3Test.razor index 36adadd33..a6e77cd08 100644 --- a/docs/samples/tests/razor/RenderFragmentParams3Test.razor +++ b/docs/samples/tests/razor/RenderFragmentParams3Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/RenderFragmentParams4Test.razor b/docs/samples/tests/razor/RenderFragmentParams4Test.razor index 0fa477306..6976927bc 100644 --- a/docs/samples/tests/razor/RenderFragmentParams4Test.razor +++ b/docs/samples/tests/razor/RenderFragmentParams4Test.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/razor/TwoWayBindingTest.razor b/docs/samples/tests/razor/TwoWayBindingTest.razor index 5edd20db1..c8be81db4 100644 --- a/docs/samples/tests/razor/TwoWayBindingTest.razor +++ b/docs/samples/tests/razor/TwoWayBindingTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { [Fact] diff --git a/docs/samples/tests/razor/UnmatchedParamsTest.razor b/docs/samples/tests/razor/UnmatchedParamsTest.razor index f52af243f..bb1568595 100644 --- a/docs/samples/tests/razor/UnmatchedParamsTest.razor +++ b/docs/samples/tests/razor/UnmatchedParamsTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/xunit/AsyncDataTest.cs b/docs/samples/tests/xunit/AsyncDataTest.cs index 9731faf40..676a780b4 100644 --- a/docs/samples/tests/xunit/AsyncDataTest.cs +++ b/docs/samples/tests/xunit/AsyncDataTest.cs @@ -6,7 +6,7 @@ namespace Bunit.Docs.Samples; -public class AsyncDataTest : TestContext +public class AsyncDataTest : BunitContext { [Fact] public void LoadDataAsync() diff --git a/docs/samples/tests/xunit/CascadingParams1Test.cs b/docs/samples/tests/xunit/CascadingParams1Test.cs index 9bb71cd97..25285b32b 100644 --- a/docs/samples/tests/xunit/CascadingParams1Test.cs +++ b/docs/samples/tests/xunit/CascadingParams1Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class CascadingParams1Test : TestContext +public class CascadingParams1Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/CascadingParams2Test.cs b/docs/samples/tests/xunit/CascadingParams2Test.cs index 193e593fa..30f537acf 100644 --- a/docs/samples/tests/xunit/CascadingParams2Test.cs +++ b/docs/samples/tests/xunit/CascadingParams2Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class CascadingParams2Test : TestContext +public class CascadingParams2Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/CascadingParams3Test.cs b/docs/samples/tests/xunit/CascadingParams3Test.cs index 0a6e49d26..4df60541a 100644 --- a/docs/samples/tests/xunit/CascadingParams3Test.cs +++ b/docs/samples/tests/xunit/CascadingParams3Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class CascadingParams3Test : TestContext +public class CascadingParams3Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ChildContentParams1Test.cs b/docs/samples/tests/xunit/ChildContentParams1Test.cs index b480642da..f6c07a368 100644 --- a/docs/samples/tests/xunit/ChildContentParams1Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams1Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class ChildContentParams1Test : TestContext +public class ChildContentParams1Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ChildContentParams2Test.cs b/docs/samples/tests/xunit/ChildContentParams2Test.cs index 8c0c2b4f9..26835567d 100644 --- a/docs/samples/tests/xunit/ChildContentParams2Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams2Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class ChildContentParams2Test : TestContext +public class ChildContentParams2Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ChildContentParams3Test.cs b/docs/samples/tests/xunit/ChildContentParams3Test.cs index 880c4442a..a31e67954 100644 --- a/docs/samples/tests/xunit/ChildContentParams3Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams3Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class ChildContentParams3Test : TestContext +public class ChildContentParams3Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ChildContentParams4Test.cs b/docs/samples/tests/xunit/ChildContentParams4Test.cs index 54388d9e5..b2c2477bb 100644 --- a/docs/samples/tests/xunit/ChildContentParams4Test.cs +++ b/docs/samples/tests/xunit/ChildContentParams4Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class ChildContentParams4Test : TestContext +public class ChildContentParams4Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ClickMeTest.cs b/docs/samples/tests/xunit/ClickMeTest.cs index 6c14410a6..23b7284f2 100644 --- a/docs/samples/tests/xunit/ClickMeTest.cs +++ b/docs/samples/tests/xunit/ClickMeTest.cs @@ -4,7 +4,7 @@ namespace Bunit.Docs.Samples; -public class ClickMeTest : TestContext +public class ClickMeTest : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs b/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs index 47893e27b..3cce43104 100644 --- a/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs +++ b/docs/samples/tests/xunit/ComponentFactoryExampleTest.cs @@ -4,7 +4,7 @@ namespace Bunit.Docs.Samples { - public class ComponentFactoryExampleTest : TestContext + public class ComponentFactoryExampleTest : BunitContext { [Fact] public void ReplacesFooWithBarDuringTest() diff --git a/docs/samples/tests/xunit/CounterTest.cs b/docs/samples/tests/xunit/CounterTest.cs index 7f44ad736..2f76a42b0 100644 --- a/docs/samples/tests/xunit/CounterTest.cs +++ b/docs/samples/tests/xunit/CounterTest.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; -public class CounterTest : TestContext +public class CounterTest : BunitContext { [Fact] public void CounterShouldIncrementWhenClicked() diff --git a/docs/samples/tests/xunit/CounterTestWithCtx.cs b/docs/samples/tests/xunit/CounterTestWithCtx.cs index 9816f107b..b9a244d57 100644 --- a/docs/samples/tests/xunit/CounterTestWithCtx.cs +++ b/docs/samples/tests/xunit/CounterTestWithCtx.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; -public class CounterTestWithCtx : TestContext +public class CounterTestWithCtx : BunitContext { [Fact] public void CounterShouldIncrementWhenClicked() diff --git a/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs b/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs index ae26475cf..f23cfb58f 100644 --- a/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs +++ b/docs/samples/tests/xunit/CounterWithFancyParagraphTest.cs @@ -5,7 +5,7 @@ namespace Bunit.Docs.Samples { - public class CounterWithFancyParagraphTest : TestContext + public class CounterWithFancyParagraphTest : BunitContext { [Fact] public void CounterShouldIncrementWhenClicked_Moq() diff --git a/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs b/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs index cee28d37a..bc910af74 100644 --- a/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs +++ b/docs/samples/tests/xunit/CustomServiceProviderFactoryUsage.cs @@ -7,7 +7,7 @@ using Xunit; namespace Bunit.Docs.Samples; -public class CustomServiceProviderFactoryUsage : TestContext +public class CustomServiceProviderFactoryUsage : BunitContext { [Fact] public void CustomServiceProviderViaFactoryReturns() @@ -49,10 +49,10 @@ void ConfigureContainer(ContainerBuilder containerBuilder) //get a service which was installed in the bUnit ServiceCollection - var testContext = Services.GetService(); + var BunitContext = Services.GetService(); - Assert.NotNull(testContext); - Assert.Equal(this, testContext); + Assert.NotNull(BunitContext); + Assert.Equal(this, BunitContext); } [Fact] @@ -81,9 +81,9 @@ ILifetimeScope ConfigureContainer(IServiceCollection services) //get a service which was installed in the bUnit ServiceCollection - var testContext = Services.GetService(); + var BunitContext = Services.GetService(); - Assert.NotNull(testContext); - Assert.Equal(this, testContext); + Assert.NotNull(BunitContext); + Assert.Equal(this, BunitContext); } } diff --git a/docs/samples/tests/xunit/DisposeComponentsTest.cs b/docs/samples/tests/xunit/DisposeComponentsTest.cs index 186cd6667..1f6e30b84 100644 --- a/docs/samples/tests/xunit/DisposeComponentsTest.cs +++ b/docs/samples/tests/xunit/DisposeComponentsTest.cs @@ -5,7 +5,7 @@ namespace Bunit.Docs.Samples; -public class DisposeComponentsTest : TestContext +public class DisposeComponentsTest : BunitContext { [Fact] public void DisposeElements() diff --git a/docs/samples/tests/xunit/EventCallbackParamsTest.cs b/docs/samples/tests/xunit/EventCallbackParamsTest.cs index 782fa4021..536a4c23d 100644 --- a/docs/samples/tests/xunit/EventCallbackParamsTest.cs +++ b/docs/samples/tests/xunit/EventCallbackParamsTest.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class EventCallbackParamsTest : TestContext +public class EventCallbackParamsTest : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/FallBackServiceProviderUsage.cs b/docs/samples/tests/xunit/FallBackServiceProviderUsage.cs index e62c7122d..d5e94739e 100644 --- a/docs/samples/tests/xunit/FallBackServiceProviderUsage.cs +++ b/docs/samples/tests/xunit/FallBackServiceProviderUsage.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; -public class FallBackServiceProviderUsageExample : TestContext +public class FallBackServiceProviderUsageExample : BunitContext { [Fact] public void FallBackServiceProviderReturns() diff --git a/docs/samples/tests/xunit/HelloWorldExplicitContextRazorTest.razor b/docs/samples/tests/xunit/HelloWorldExplicitContextRazorTest.razor index 06141d70c..44c005ba3 100644 --- a/docs/samples/tests/xunit/HelloWorldExplicitContextRazorTest.razor +++ b/docs/samples/tests/xunit/HelloWorldExplicitContextRazorTest.razor @@ -4,7 +4,7 @@ public void HelloWorldComponentRendersCorrectly() { // Arrange - using var ctx = new TestContext(); + using var ctx = new BunitContext(); // Act var cut = ctx.Render(@); diff --git a/docs/samples/tests/xunit/HelloWorldExplicitContextTest.cs b/docs/samples/tests/xunit/HelloWorldExplicitContextTest.cs index 8886b7fe6..437f36b99 100644 --- a/docs/samples/tests/xunit/HelloWorldExplicitContextTest.cs +++ b/docs/samples/tests/xunit/HelloWorldExplicitContextTest.cs @@ -9,7 +9,7 @@ public class HelloWorldExplicitContext public void HelloWorldComponentRendersCorrectly() { // Arrange - using var ctx = new TestContext(); + using var ctx = new BunitContext(); // Act var cut = ctx.Render(); diff --git a/docs/samples/tests/xunit/HelloWorldImplicitContextRazorTest.razor b/docs/samples/tests/xunit/HelloWorldImplicitContextRazorTest.razor index 1c533a5e6..6da64ee44 100644 --- a/docs/samples/tests/xunit/HelloWorldImplicitContextRazorTest.razor +++ b/docs/samples/tests/xunit/HelloWorldImplicitContextRazorTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/docs/samples/tests/xunit/HelloWorldRazorTest.razor b/docs/samples/tests/xunit/HelloWorldRazorTest.razor index 11dc99d6e..977b9e008 100644 --- a/docs/samples/tests/xunit/HelloWorldRazorTest.razor +++ b/docs/samples/tests/xunit/HelloWorldRazorTest.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { [Fact] diff --git a/docs/samples/tests/xunit/HelloWorldTest.cs b/docs/samples/tests/xunit/HelloWorldTest.cs index 48ccf4411..bec8f1f56 100644 --- a/docs/samples/tests/xunit/HelloWorldTest.cs +++ b/docs/samples/tests/xunit/HelloWorldTest.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; using Xunit; using Bunit; -public class HelloWorldTest : TestContext +public class HelloWorldTest : BunitContext { [Fact] public void HelloWorldComponentRendersCorrectly() diff --git a/docs/samples/tests/xunit/InjectAuthServiceTest.cs b/docs/samples/tests/xunit/InjectAuthServiceTest.cs index 5b2ff5d7c..b66c98cdd 100644 --- a/docs/samples/tests/xunit/InjectAuthServiceTest.cs +++ b/docs/samples/tests/xunit/InjectAuthServiceTest.cs @@ -4,7 +4,7 @@ namespace Bunit.Docs.Samples; -public class InjectAuthServiceTest : TestContext +public class InjectAuthServiceTest : BunitContext { [Fact(DisplayName = "Use AuthenticationStateProvider service with authenticated and authorized user")] public void Test001() diff --git a/docs/samples/tests/xunit/NestedComponentTest.cs b/docs/samples/tests/xunit/NestedComponentTest.cs index ff18ec239..72be88d38 100644 --- a/docs/samples/tests/xunit/NestedComponentTest.cs +++ b/docs/samples/tests/xunit/NestedComponentTest.cs @@ -6,7 +6,7 @@ namespace Bunit.Docs.Samples; -public class NestedComponentTest : TestContext +public class NestedComponentTest : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/NonBlazorTypesParamsTest.cs b/docs/samples/tests/xunit/NonBlazorTypesParamsTest.cs index 1a867eea0..640821b7e 100644 --- a/docs/samples/tests/xunit/NonBlazorTypesParamsTest.cs +++ b/docs/samples/tests/xunit/NonBlazorTypesParamsTest.cs @@ -7,7 +7,7 @@ namespace Bunit.Docs.Samples; -public class NonBlazorTypesParamsTest : TestContext +public class NonBlazorTypesParamsTest : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/ReRenderTest.cs b/docs/samples/tests/xunit/ReRenderTest.cs index 696a5c49f..6684ac8b4 100644 --- a/docs/samples/tests/xunit/ReRenderTest.cs +++ b/docs/samples/tests/xunit/ReRenderTest.cs @@ -6,7 +6,7 @@ namespace Bunit.Docs.Samples; -public class ReRenderTest : TestContext +public class ReRenderTest : BunitContext { [Fact] public void RenderAgainUsingRender() diff --git a/docs/samples/tests/xunit/RenderFragmentParams1Test.cs b/docs/samples/tests/xunit/RenderFragmentParams1Test.cs index bc24aaa7c..eb3949fe6 100644 --- a/docs/samples/tests/xunit/RenderFragmentParams1Test.cs +++ b/docs/samples/tests/xunit/RenderFragmentParams1Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class RenderFragmentParams1Test : TestContext +public class RenderFragmentParams1Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/RenderFragmentParams2Test.cs b/docs/samples/tests/xunit/RenderFragmentParams2Test.cs index 1f1ce0cbf..598f5e9d6 100644 --- a/docs/samples/tests/xunit/RenderFragmentParams2Test.cs +++ b/docs/samples/tests/xunit/RenderFragmentParams2Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class RenderFragmentParams2Test : TestContext +public class RenderFragmentParams2Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/RenderFragmentParams3Test.cs b/docs/samples/tests/xunit/RenderFragmentParams3Test.cs index 677778ba9..33825170d 100644 --- a/docs/samples/tests/xunit/RenderFragmentParams3Test.cs +++ b/docs/samples/tests/xunit/RenderFragmentParams3Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class RenderFragmentParams3Test : TestContext +public class RenderFragmentParams3Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/RenderFragmentParams4Test.cs b/docs/samples/tests/xunit/RenderFragmentParams4Test.cs index ddcf796a5..d34f4f04a 100644 --- a/docs/samples/tests/xunit/RenderFragmentParams4Test.cs +++ b/docs/samples/tests/xunit/RenderFragmentParams4Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class RenderFragmentParams4Test : TestContext +public class RenderFragmentParams4Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/RenderTreeTest.cs b/docs/samples/tests/xunit/RenderTreeTest.cs index 09c1e9ae3..3e2dc67d5 100644 --- a/docs/samples/tests/xunit/RenderTreeTest.cs +++ b/docs/samples/tests/xunit/RenderTreeTest.cs @@ -7,7 +7,7 @@ namespace Bunit.Docs.Samples; -public class RenderTreeTest : TestContext +public class RenderTreeTest : BunitContext { [Fact] public void PrintCascadingValueTest() diff --git a/docs/samples/tests/xunit/SemanticHtmlTest.cs b/docs/samples/tests/xunit/SemanticHtmlTest.cs index 6ced88630..d07b1f580 100644 --- a/docs/samples/tests/xunit/SemanticHtmlTest.cs +++ b/docs/samples/tests/xunit/SemanticHtmlTest.cs @@ -6,7 +6,7 @@ namespace Bunit.Docs.Samples; -public class SemanticHtmlTest : TestContext +public class SemanticHtmlTest : BunitContext { [Fact] public void InitialHtmlIsCorrect() diff --git a/docs/samples/tests/xunit/TemplateParams1Test.cs b/docs/samples/tests/xunit/TemplateParams1Test.cs index 1b3e5ba8d..bd37c667a 100644 --- a/docs/samples/tests/xunit/TemplateParams1Test.cs +++ b/docs/samples/tests/xunit/TemplateParams1Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class TemplateParams1Test : TestContext +public class TemplateParams1Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/TemplateParams2Test.cs b/docs/samples/tests/xunit/TemplateParams2Test.cs index 7db47e08b..cfb629b7f 100644 --- a/docs/samples/tests/xunit/TemplateParams2Test.cs +++ b/docs/samples/tests/xunit/TemplateParams2Test.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class TemplateParams2Test : TestContext +public class TemplateParams2Test : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/TwoWayBindingTest.cs b/docs/samples/tests/xunit/TwoWayBindingTest.cs index 8ac4edece..2de2445be 100644 --- a/docs/samples/tests/xunit/TwoWayBindingTest.cs +++ b/docs/samples/tests/xunit/TwoWayBindingTest.cs @@ -2,7 +2,7 @@ namespace Bunit.Docs.Samples; -public class TwoWayBindingTest : TestContext +public class TwoWayBindingTest : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/UnmatchedParamsTest.cs b/docs/samples/tests/xunit/UnmatchedParamsTest.cs index 9f6f39040..3e67f5e64 100644 --- a/docs/samples/tests/xunit/UnmatchedParamsTest.cs +++ b/docs/samples/tests/xunit/UnmatchedParamsTest.cs @@ -8,7 +8,7 @@ namespace Bunit.Docs.Samples; -public class UnmatchedParamsTest : TestContext +public class UnmatchedParamsTest : BunitContext { [Fact] public void Test() diff --git a/docs/samples/tests/xunit/UserInfoTest.cs b/docs/samples/tests/xunit/UserInfoTest.cs index cca924096..7c1cc03ed 100644 --- a/docs/samples/tests/xunit/UserInfoTest.cs +++ b/docs/samples/tests/xunit/UserInfoTest.cs @@ -3,7 +3,7 @@ namespace Bunit.Docs.Samples; -public class UserInfoTest : TestContext +public class UserInfoTest : BunitContext { [Fact(DisplayName = "UserInfo with unauthenticated user")] public void Test001() diff --git a/docs/samples/tests/xunit/UserRightsTest.cs b/docs/samples/tests/xunit/UserRightsTest.cs index 47fb3638e..89692764a 100644 --- a/docs/samples/tests/xunit/UserRightsTest.cs +++ b/docs/samples/tests/xunit/UserRightsTest.cs @@ -5,7 +5,7 @@ namespace Bunit.Docs.Samples; -public class UserRightsTest : TestContext +public class UserRightsTest : BunitContext { [Fact(DisplayName = "No roles or policies")] public void Test001() diff --git a/docs/samples/tests/xunit/VerifyMarkupExamples.cs b/docs/samples/tests/xunit/VerifyMarkupExamples.cs index fb0c9b169..c640de3cf 100644 --- a/docs/samples/tests/xunit/VerifyMarkupExamples.cs +++ b/docs/samples/tests/xunit/VerifyMarkupExamples.cs @@ -6,7 +6,7 @@ namespace Bunit.Docs.Samples; -public class VerifyMarkupExamples : TestContext +public class VerifyMarkupExamples : BunitContext { [Fact] public void RawMarkupVerify() diff --git a/docs/samples/tests/xunit/WeatherForecastsTest.cs b/docs/samples/tests/xunit/WeatherForecastsTest.cs index c8a42a5c5..79d9f71bc 100644 --- a/docs/samples/tests/xunit/WeatherForecastsTest.cs +++ b/docs/samples/tests/xunit/WeatherForecastsTest.cs @@ -7,7 +7,7 @@ namespace Bunit.Docs.Samples; -public class WeatherForecastsTest : TestContext +public class WeatherForecastsTest : BunitContext { [Fact] public void ServicesIsInjectedCorrectly() diff --git a/docs/site/docs/extensions/bunit-generators.md b/docs/site/docs/extensions/bunit-generators.md index 8f24f1681..c9c072908 100644 --- a/docs/site/docs/extensions/bunit-generators.md +++ b/docs/site/docs/extensions/bunit-generators.md @@ -67,7 +67,7 @@ The general setup for the given component above looks like this: ```csharp namespace MyTest; -public class FeatureTests : TestContext +public class FeatureTests : BunitContext { [Fact] public void Test() diff --git a/docs/site/docs/getting-started/writing-tests.md b/docs/site/docs/getting-started/writing-tests.md index b2a744e2b..5edca9a8f 100644 --- a/docs/site/docs/getting-started/writing-tests.md +++ b/docs/site/docs/getting-started/writing-tests.md @@ -9,7 +9,7 @@ Testing Blazor components is a little different from testing regular C# classes: Use **bUnit** to render the component under test, pass in its parameters, inject required services, and access the rendered component instance and the markup it has produced. -Rendering a component happens through bUnit's . The result of the rendering is an `RenderedComponent`, referred to as a "rendered component", that provides access to the component instance and the markup produced by the component. +Rendering a component happens through bUnit's . The result of the rendering is an `RenderedComponent`, referred to as a "rendered component", that provides access to the component instance and the markup produced by the component. ## Write tests in `.cs` or `.razor` files @@ -50,25 +50,15 @@ With that in place, lets look at a simple example that tests the following `. This base class offers the majority of functions. -2. Renders the `` component using , which is done through the `Render(RenderFragment)` method. We cover passing parameters to components on the page. +1. Inherits from the bUnit . This base class offers the majority of functions. +2. Renders the `` component using , which is done through the `Render(RenderFragment)` method. We cover passing parameters to components on the page. 3. Verifies the rendered markup from the `` component using the `MarkupMatches` method. The `MarkupMatches` method performs a semantic comparison of the expected markup with the rendered markup. # [NUnit](#tab/nunit) [!code-cshtml[HelloWorldRazorTest.razor](../../../samples/tests/nunit/HelloWorldRazorTest.razor)] -Since NUnit instantiates a test class only once for all tests inside it, we cannot simply inherit directly from as we want a fresh instance of for each test. Instead, we create a helper class, `BunitTestContext`, listed below, and use that to hook into NUnit's `[SetUp]` and `[TearDown]` methods, which run before and after each test. - -[!code-csharp[BunitTestContext.cs](../../../samples/tests/nunit/BunitTestContext.cs#L3-L13)] - -The test above does the following: - -1. Inherits from the `BunitTestContext` above. This base class offers the majority of functions. -2. Renders the `` component using , which is done through the `Render(RenderFragment)` method. We cover passing parameters to components on the page. -3. Verifies the rendered markup from the `` component using the `MarkupMatches` method. The `MarkupMatches` method performs a semantic comparison of the expected markup with the rendered markup. - -Alternatively, use the [LifeCycle.InstancePerTestCase](https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html) attribute (introduced in NUnit 3.13) so that a new instance of the test class is created for each test removing the need for the wrapper. +Use the [LifeCycle.InstancePerTestCase](https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html) attribute (introduced in NUnit 3.13) so that a new instance of the test class is created for each test removing the need for the wrapper. [!code-csharp[HelloWorldInstancePerTestCase.cs](../../../samples/tests/nunit/HelloWorldInstancePerTestCase.cs#L5-L17)] @@ -76,15 +66,6 @@ Alternatively, use the [LifeCycle.InstancePerTestCase](https://docs.nunit.org/ar [!code-cshtml[HelloWorldRazorTest.razor](../../../samples/tests/mstest/HelloWorldRazorTest.razor)] -Since MSTest instantiates a test class only once for all tests inside it, we cannot simply inherit directly from as we want a fresh instance of for each test. Instead, we create a helper class, `BunitTestContext`, listed below, and use that to hook into MSTest's `[TestInitialize]` and `[TestCleanup]` methods. This runs before and after each test. - -[!code-csharp[BunitTestContext.cs](../../../samples/tests/mstest/BunitTestContext.cs#L3-L13)] - -The test above does the following: - -1. Inherits from the `BunitTestContext` above. This base class offers the majority of functions. -2. Renders the `` component using , which is done through the `Render(RenderFragment)` method. We cover passing parameters to components on the page. -3. Verifies the rendered markup from the `` component using the `MarkupMatches` method. The `MarkupMatches` method performs a semantic comparison of the expected markup with the rendered markup. *** @@ -136,22 +117,18 @@ This is a simple example of writing tests in `.cs` files which tests the followi The test above does the following: -1. Inherits from the bUnit's `TestContext`. This base class offers the majority of functions. -2. Renders the `` component using , which is done through the method. We cover passing parameters to components on the page. +1. Inherits from the bUnit's `BunitContext`. This base class offers the majority of functions. +2. Renders the `` component using , which is done through the method. We cover passing parameters to components on the page. 3. Verifies the rendered markup from the `` component using the `MarkupMatches` method. The `MarkupMatches` method performs a semantic comparison of the expected markup with the rendered markup. # [NUnit](#tab/nunit) [!code-csharp[HelloWorldTest.cs](../../../samples/tests/nunit/HelloWorldTest.cs#L3-L20)] -Since NUnit instantiates a test class only once for all tests inside it, we cannot simply inherit directly from as we want a fresh instance of for each test. Instead, we create a helper class, `BunitTestContext`, listed below, and use that to hook into NUnit's `[SetUp]` and `[TearDown]` methods, which run before and after each test. - -[!code-csharp[BunitTestContext.cs](../../../samples/tests/nunit/BunitTestContext.cs#L3-L13)] - The test above does the following: -1. Inherits from the `BunitTestContext` listed above. This base class offers the majority of functions. -2. Renders the `` component using , which is done through the method. We cover passing parameters to components on the page. +1. Inherits from the `BunitContext` listed above. This base class offers the majority of functions. +2. Renders the `` component using , which is done through the method. We cover passing parameters to components on the page. 3. Verifies the rendered markup from the `` component using the `MarkupMatches` method. The `MarkupMatches` method performs a semantic comparison of the expected markup with the rendered markup. Alternatively, use the [LifeCycle.InstancePerTestCase](https://docs.nunit.org/articles/nunit/writing-tests/attributes/fixturelifecycle.html) attribute (introduced in NUnit 3.13) so that a new instance of the test class is created for each test removing the need for the wrapper. @@ -162,14 +139,10 @@ Alternatively, use the [LifeCycle.InstancePerTestCase](https://docs.nunit.org/ar [!code-csharp[HelloWorldTest.cs](../../../samples/tests/mstest/HelloWorldTest.cs#L3-L20)] -Since MSTest instantiates a test class only once for all tests inside it, we cannot simply inherit directly from as we want a fresh instance of for each test. Instead, we create a helper class, `BunitTestContext`, listed below, and use that to hook into MSTest's `[TestInitialize]` and `[TestCleanup]` methods. This runs before and after each test. - -[!code-csharp[BunitTestContext.cs](../../../samples/tests/mstest/BunitTestContext.cs#L3-L13)] - The test above does the following: -1. Inherits from the `BunitTestContext` listed above. This base class offers the majority of functions. -2. Renders the `` component using , which is done through the method. We cover passing parameters to components on the page. +1. Inherits from the `BunitContext` listed above. This base class offers the majority of functions. +2. Renders the `` component using , which is done through the method. We cover passing parameters to components on the page. 3. Verifies the rendered markup from the `` component using the `MarkupMatches` method. The `MarkupMatches` method performs a semantic comparison of the expected markup with the rendered markup. *** @@ -180,11 +153,11 @@ The test above does the following: > [!TIP] > In bUnit tests, we like to use the abbreviation `CUT`, short for "component under test", to indicate the component that is being tested. This is inspired by the common testing abbreviation `SUT`, short for "system under test". -### Instantiate TestContext in each test +### Instantiate BunitContext in each test -If you prefer to instantiate in each test, instead of inheriting from it, you can do so. This can be useful if you have your own base class that you want to inherit from, or if you want to use a different test framework than the ones listed here. +If you prefer to instantiate in each test, instead of inheriting from it, you can do so. This can be useful if you have your own base class that you want to inherit from, or if you want to use a different test framework than the ones listed here. -Just be aware that all examples in the rest of the documentation assumes that you are inheriting from , so adjust accordingly. +Just be aware that all examples in the rest of the documentation assumes that you are inheriting from , so adjust accordingly. # [xUnit](#tab/xunit) @@ -194,17 +167,10 @@ Just be aware that all examples in the rest of the documentation assumes that yo [!code-csharp[HelloWorldExplicitContextTest.cs](../../../samples/tests/nunit/HelloWorldExplicitContextTest.cs#L6-L20)] -> [!NOTE] -> `TestContext` is an ambiguous reference - it could mean `Bunit.TestContext` or `NUnit.Framework.TestContext` - so you have to specify the `Bunit` namespace when referencing `TestContext` to resolve the ambiguity for the compiler. Alternatively, you can give bUnit's `TestContext` a different name during import, e.g.: `using BunitTestContext = Bunit.TestContext;` - # [MSTest](#tab/mstest) [!code-csharp[HelloWorldImplicitContextTest.cs](../../../samples/tests/mstest/HelloWorldExplicitContextTest.cs#L6-L21)] -> [!NOTE] -> `TestContext` is an ambiguous reference - it could mean `Bunit.TestContext` or `Microsoft.VisualStudio.TestTools.UnitTesting.TestContext` - so you have to specify the `Bunit` namespace when referencing `TestContext` to resolve the ambiguity for the compiler. Alternatively, you can give bUnit's `TestContext` a different name during import, e.g.: -> `using BunitTestContext = Bunit.TestContext;` - ## Further reading With the basics out of the way, next we will look at how to pass parameters and inject services into our component under test. After that, we will cover the ways in which we can verify the outcome of a rendering in more detail diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index 984e5389c..55f16fcb0 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -4,7 +4,7 @@ title: Disposing components and their children --- # Disposing components -To dispose all components rendered with a `TestContext`, use the [`DisposeComponents`](xref:Bunit.TestContext.DisposeComponents) method. Calling this method will dispose all rendered components, calling any `IDisposable.Dispose` or/and `IAsyncDisposable.DisposeAsync` methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components. +To dispose all components rendered with a `BunitContext`, use the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponents) method. Calling this method will dispose all rendered components, calling any `IDisposable.Dispose` or/and `IAsyncDisposable.DisposeAsync` methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components. Disposing rendered components enables testing of logic in `Dispose` methods, e.g., event handlers, that should be detached to avoid memory leaks. @@ -16,7 +16,7 @@ The following example of this: > For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Checking for exceptions -`Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.TestContext.DisposeComponents) will throw the exception to the user code: +`Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponents) will throw the exception to the user code: [!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L28-L32)] diff --git a/docs/site/docs/interaction/trigger-renders.md b/docs/site/docs/interaction/trigger-renders.md index 1e3461794..496f92d21 100644 --- a/docs/site/docs/interaction/trigger-renders.md +++ b/docs/site/docs/interaction/trigger-renders.md @@ -5,13 +5,13 @@ title: Triggering a render life cycle on a component # Triggering a render life cycle on a component -To trigger a re-render of a component under test, a reference to it through a type is needed. When using the 's `Render()` method, this is the type returned. +To trigger a re-render of a component under test, a reference to it through a type is needed. When using the 's `Render()` method, this is the type returned. -In `.razor` based tests, using the 's method also returns an (as opposed to the method which returns the more simple ). +In `.razor` based tests, using the 's method also returns an (as opposed to the method which returns the more simple ). If you have a or a in a test, but need a child component's , then use the `FindComponent()` or the `FindComponents()` methods, which traverse down the render tree and finds rendered components. -With a , it is possible to cause the component to render again directly through the [`Render()`](xref:Bunit.TestContext.Render``1(Microsoft.AspNetCore.Components.RenderFragment)) method or one of the [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods, or indirectly through the [`InvokeAsync()`](xref:Bunit.RenderedFragment.Bunit.RenderedFragmentInvokeAsyncExtensions.InvokeAsync(System.Action)) method. +With a , it is possible to cause the component to render again directly through the [`Render()`](xref:Bunit.BunitContext.Render``1(Microsoft.AspNetCore.Components.RenderFragment)) method or one of the [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods, or indirectly through the [`InvokeAsync()`](xref:Bunit.RenderedFragment.Bunit.RenderedFragmentInvokeAsyncExtensions.InvokeAsync(System.Action)) method. Let's look at how to use each of these methods to cause a re-render. diff --git a/docs/site/docs/misc-test-tips.md b/docs/site/docs/misc-test-tips.md index 5e0eacdd5..b2f6e8b4e 100644 --- a/docs/site/docs/misc-test-tips.md +++ b/docs/site/docs/misc-test-tips.md @@ -87,7 +87,7 @@ With xUnit, this can be done as follows: namespace MyTests; - public class MyComponenTest : TestContext + public class MyComponenTest : BunitContext { public MyComponenTest(ITestOutputHelper outputHelper) { diff --git a/docs/site/docs/providing-input/passing-parameters-to-components.md b/docs/site/docs/providing-input/passing-parameters-to-components.md index a6455b5ab..410b4c1e8 100644 --- a/docs/site/docs/providing-input/passing-parameters-to-components.md +++ b/docs/site/docs/providing-input/passing-parameters-to-components.md @@ -19,7 +19,7 @@ In the following sub sections, we will show both `.cs`- and `.razor`-based test > [!NOTE] > The examples below are written using **xUnit**, but the code is the same with **NUnit** and **MSTest**. > -> The example tests are inheriting from the `TestContext` as described in the page. If your test class is not inheriting from the `TestContext`, then you should explicitly instantiate the `TestContext` in your tests. The recommended way is to inherit from the `TestContext`. An example below will demonstrate how to instantiate a `TestContext` per test method. +> The example tests are inheriting from the `BunitContext` as described in the page. If your test class is not inheriting from the `BunitContext`, then you should explicitly instantiate the `BunitContext` in your tests. The recommended way is to inherit from the `BunitContext`. An example below will demonstrate how to instantiate a `BunitContext` per test method. ## Regular parameters @@ -65,7 +65,7 @@ The example uses the 's `Add` [!code-cshtml[EventCallbackParamsTest.razor](../../../samples/tests/razor/EventCallbackParamsTest.razor)] -The example passes a inline Razor template to the method. The parameters to the component is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The parameters to the component is just passed like normal in Razor code. *** @@ -89,7 +89,7 @@ The example uses the 's `AddCh [!code-cshtml[ChildContentParamsTest.razor](../../../samples/tests/razor/ChildContentParams1Test.razor)] -The example passes a inline Razor template to the method. The child content, some HTML markup, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some HTML markup, is just passed like normal in Razor code. *** @@ -107,7 +107,7 @@ The example uses the 's `AddCh [!code-cshtml[ChildContentParamsTest.razor](../../../samples/tests/razor/ChildContentParams2Test.razor)] -The example passes a inline Razor template to the method. The child content, some Razor markup, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some Razor markup, is just passed like normal in Razor code. *** @@ -127,7 +127,7 @@ The example uses the 's `AddCh [!code-cshtml[ChildContentParamsTest.razor](../../../samples/tests/razor/ChildContentParams3Test.razor)] -The example passes a inline Razor template to the method. The child content, some Razor markup, and parameters to the child component, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some Razor markup, and parameters to the child component, is just passed like normal in Razor code. *** @@ -145,7 +145,7 @@ Passing a mix of markup and components to a `ChildContent` parameter is done by [!code-cshtml[ChildContentParamsTest.razor](../../../samples/tests/razor/ChildContentParams4Test.razor)] -The example passes a inline Razor template to the method. The child content, some Razor markup, and parameters to the child component, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some Razor markup, and parameters to the child component, is just passed like normal in Razor code. *** @@ -171,7 +171,7 @@ The example uses the 's `Add` [!code-cshtml[RenderFragmentParamsTest.razor](../../../samples/tests/razor/RenderFragmentParams1Test.razor)] -The example passes a inline Razor template to the method. The child content, some HTML markup, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some HTML markup, is just passed like normal in Razor code. *** @@ -189,7 +189,7 @@ The example uses the 's `Add method. The child content, some Razor markup, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some Razor markup, is just passed like normal in Razor code. *** @@ -209,7 +209,7 @@ The example uses the 's `Add method. The child content, some Razor markup, and parameters to the child component, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some Razor markup, and parameters to the child component, is just passed like normal in Razor code. *** @@ -227,7 +227,7 @@ Passing a mix of markup and components to a `RenderFragment` parameter is simply [!code-cshtml[RenderFragmentParamsTest.razor](../../../samples/tests/razor/RenderFragmentParams4Test.razor)] -The example passes a inline Razor template to the method. The child content, some HTML and Razor markup, and parameters to the child component, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child content, some HTML and Razor markup, and parameters to the child component, is just passed like normal in Razor code. *** @@ -257,7 +257,7 @@ The delegate creates a simple markup string in the example. [!code-cshtml[TemplateParamsTest.razor](../../../samples/tests/razor/TemplateParams1Test.razor)] -The example passes a inline Razor template to the method. The child template content, some HTML markup, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child template content, some HTML markup, is just passed like normal in Razor code. **NOTE:** Before the .NET 6 version of the Blazor compiler, this example does not work. @@ -279,7 +279,7 @@ The example creates a template with the `` component listed above. [!code-cshtml[TemplateParamsTest.razor](../../../samples/tests/razor/TemplateParams2Test.razor)] -The example passes a inline Razor template to the method. The child template content, some HTML and Razor markup, is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The child template content, some HTML and Razor markup, is just passed like normal in Razor code. **NOTE:** Before the .NET 6 version of the Blazor compiler, this example does not work. @@ -303,7 +303,7 @@ The examples passes in the parameter `some-unknown-param` with the value `a valu [!code-cshtml[UnmatchedParamsTest.razor](../../../samples/tests/razor/UnmatchedParamsTest.razor)] -The example passes a inline Razor template to the method. The parameter is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The parameter is just passed like normal in Razor code. *** @@ -329,7 +329,7 @@ The example pass the variable `isDarkTheme` to the cascading parameter `IsDarkTh [!code-cshtml[CascadingParamsTest.razor](../../../samples/tests/razor/CascadingParams1Test.razor)] -The example passes a inline Razor template to the method. The cascading value is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The cascading value is just passed like normal in Razor code. *** @@ -347,7 +347,7 @@ The example pass in the value `Name of User` to the cascading parameter with the [!code-cshtml[CascadingParamsTest.razor](../../../samples/tests/razor/CascadingParams2Test.razor)] -The example passes a inline Razor template to the method. The cascading value is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The cascading value is just passed like normal in Razor code. *** @@ -365,7 +365,7 @@ The example passes both the unnamed `IsDarkTheme` cascading parameter and the tw [!code-cshtml[CascadingParamsTest.razor](../../../samples/tests/razor/CascadingParams3Test.razor)] -The example passes a inline Razor template to the method. The cascading value is just passed like normal in Razor code. +The example passes a inline Razor template to the method. The cascading value is just passed like normal in Razor code. *** @@ -406,11 +406,11 @@ The example uses the `Bind` method to setup two-way binding between the `Value` The example uses the standard `@bind-Value` directive in Blazor to set up two way binding between the `Value` parameter and `ValueChanged` parameter and the local variable in the test method (`currentValue`). > [!WARNING] -> When using `@bind` in conjunction with razor test-files the razor component should **not** inherit from `ComponentBase` (which is the default). The simplest solution would be to inherit from `TestContext` (as seen in the example above) which also brings the benefits as described on top of this page. +> When using `@bind` in conjunction with razor test-files the razor component should **not** inherit from `ComponentBase` (which is the default). The simplest solution would be to inherit from `BunitContext` (as seen in the example above) which also brings the benefits as described on top of this page. *** -## `TestContext` per test method -There are scenarios where it is not possible or not desirable to inherit from `TestContext` in the test class. In those cases, it is possible to create a new `TestContext` instance per test method. As the `TestContext` class implements `IDisposable`, it is recommended to use the `using` statement to ensure that the instance is disposed of after the test method has run. +## `BunitContext` per test method +There are scenarios where it is not possible or not desirable to inherit from `BunitContext` in the test class. In those cases, it is possible to create a new `BunitContext` instance per test method. As the `BunitContext` class implements `IDisposable`, it is recommended to use the `using` statement to ensure that the instance is disposed of after the test method has run. # [C# test code](#tab/csharp) @@ -429,9 +429,9 @@ When the razor syntax is used and the test throws the following exception: This usually means that the test class (Blazor component where the tests is declared in) is direclty inheriting from `ComponentBase`, as is the default for all Blazor components. -The solution is to inherit from bUnits `TestContext` instead, i.e.: +The solution is to inherit from bUnits `BunitContext` instead, i.e.: ```razor -@inherits TestContext +@inherits BunitContext @code { [Fact] @@ -444,9 +444,9 @@ The solution is to inherit from bUnits `TestContext` instead, i.e.: ## Limitations of rendering a `RenderFragment` inside a test -When rendering a `RenderFragment` using the method, the created is static. This means that it will not re-render even if events are triggered. +When rendering a `RenderFragment` using the method, the created is static. This means that it will not re-render even if events are triggered. ```razor -@inherits TestContext +@inherits BunitContext @code { [Fact] @@ -483,7 +483,7 @@ For example: A simple example of how to test a component that receives parameters from the query string: ```razor -@inherits TestContext +@inherits BunitContext @code { [Fact] diff --git a/docs/site/docs/providing-input/root-render-tree.md b/docs/site/docs/providing-input/root-render-tree.md index cb57249e4..7d7bab4d6 100644 --- a/docs/site/docs/providing-input/root-render-tree.md +++ b/docs/site/docs/providing-input/root-render-tree.md @@ -7,7 +7,7 @@ title: Controlling the root render tree The root render tree, the render tree in which components under test are rendered, can be added to before components are rendered with bUnit's test context. This is mostly useful when a component under test, or a component it depends on, must be rendered inside another component, that provides a cascading value to it. -For example, when using Blazor’s authentication, it is common to add the `CascadingAuthenticationState` component higher up the render tree, such that it can provide authentication state to those components below it that need it. Adding this through the property on the type makes it possible to add it once in a shared setup method, and not have to do so in every test method during the call to [`Render()`](xref:Bunit.Rendering.RootRenderTree.Add``1(System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})). +For example, when using Blazor’s authentication, it is common to add the `CascadingAuthenticationState` component higher up the render tree, such that it can provide authentication state to those components below it that need it. Adding this through the property on the type makes it possible to add it once in a shared setup method, and not have to do so in every test method during the call to [`Render()`](xref:Bunit.Rendering.RootRenderTree.Add``1(System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})). This can also be useful when writing tests that use a third-party component library, that require a special root component to be added to the render tree, but which otherwise don’t change between tests. diff --git a/docs/site/docs/providing-input/substituting-components.md b/docs/site/docs/providing-input/substituting-components.md index 8d6f81c1f..eb946c600 100644 --- a/docs/site/docs/providing-input/substituting-components.md +++ b/docs/site/docs/providing-input/substituting-components.md @@ -7,7 +7,7 @@ title: Substituting (mocking) component bUnit makes it possible to substitute child components of a component under test with other components, e.g. mock components. This makes it possible to isolate a component under test from other components it depends on, e.g. 3rd party components. -To substitute a component during a test, you must register the substitute, or a substitute factory, with the `ComponentFactories` collection on bUnit's `TestContext`. +To substitute a component during a test, you must register the substitute, or a substitute factory, with the `ComponentFactories` collection on bUnit's `BunitContext`. > [!NOTE] > This feature is only available for test projects that target .NET 5 or later. diff --git a/docs/site/docs/test-doubles/auth.md b/docs/site/docs/test-doubles/auth.md index 85527296e..d366355bd 100644 --- a/docs/site/docs/test-doubles/auth.md +++ b/docs/site/docs/test-doubles/auth.md @@ -15,10 +15,10 @@ The test implementation of Blazor's authentication and authorization can be put - **Authenticated** and **authorized** - **Authenticated** and **authorized** with one or more **roles**, **claims**, and/or **policies** -bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.TestContext.AddAuthorization(Bunit.TestContext)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. +bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.BunitContext.AddAuthorization(Bunit.BunitContext)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. > [!NOTE] -> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.TestContext.AddAuthorization(Bunit.TestContext)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `AddAuthorization()`. +> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.BunitContext.AddAuthorization(Bunit.BunitContext)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `AddAuthorization()`. The following sections show how to set each of these states in a test. diff --git a/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md b/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md index 49175fb54..70e628f4e 100644 --- a/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md +++ b/docs/site/docs/test-doubles/fake-webassemblyhostenvironment.md @@ -5,7 +5,7 @@ title: Adding IWebAssemblyHostEnvironment # Adding `IWebAssemblyHostEnvironment` -bUnit has itws own implementation of Blazor's `IWebAssemblyHostEnvironment` built-in, which is added by default to bUnit's `TestContext.Services` service provider. That means nothing special is needed to test components that depend on `IWebAssemblyHostEnvironment`, as it is already available by default. +bUnit has itws own implementation of Blazor's `IWebAssemblyHostEnvironment` built-in, which is added by default to bUnit's `BunitContext.Services` service provider. That means nothing special is needed to test components that depend on `IWebAssemblyHostEnvironment`, as it is already available by default. Out of the box, the implementation has its `Environment` property set to `production`, and its `BaseAddress` set to `/`. diff --git a/docs/site/docs/test-doubles/mocking-localizer.md b/docs/site/docs/test-doubles/mocking-localizer.md index 4a6dbbbde..3bd696c80 100644 --- a/docs/site/docs/test-doubles/mocking-localizer.md +++ b/docs/site/docs/test-doubles/mocking-localizer.md @@ -6,7 +6,7 @@ title: Mocking Localization via IStringLocalizer

    There are just two steps. First in your setup add the following:

    ```csharp -TestContext.Services.AddLocalization(); +BunitContext.Services.AddLocalization(); ```

    Then in your test code, when you need the localized string to compare, you write the following:

    diff --git a/docs/site/docs/test-doubles/navigation-manager.md b/docs/site/docs/test-doubles/navigation-manager.md index 0d3dc3795..1dff663a2 100644 --- a/docs/site/docs/test-doubles/navigation-manager.md +++ b/docs/site/docs/test-doubles/navigation-manager.md @@ -5,7 +5,7 @@ title: Adding NavigationManager # Adding `NavigationManager` -bUnit has its own version of Blazor's `NavigationManager` built-in, which is added by default to bUnit's `TestContext.Services` service provider. That means nothing special is needed to test components that depend on `NavigationManager`, as it is already available by default. +bUnit has its own version of Blazor's `NavigationManager` built-in, which is added by default to bUnit's `BunitContext.Services` service provider. That means nothing special is needed to test components that depend on `NavigationManager`, as it is already available by default. ## Verify `NavigationManager` interactions diff --git a/docs/site/docs/test-doubles/persistentcomponentstate.md b/docs/site/docs/test-doubles/persistentcomponentstate.md index dc9e99d77..e5e269d10 100644 --- a/docs/site/docs/test-doubles/persistentcomponentstate.md +++ b/docs/site/docs/test-doubles/persistentcomponentstate.md @@ -9,7 +9,7 @@ bUnit comes with its own version of the `PersistentComponentState` type in Blazo ## Using the `PersistentComponentState` -To use the `PersistentComponentState` in bUnit, call the `AddBunitPersistentComponentState` extension method on `TestContext`: +To use the `PersistentComponentState` in bUnit, call the `AddBunitPersistentComponentState` extension method on `BunitContext`: ```csharp var state = AddBunitPersistentComponentState(); diff --git a/docs/site/docs/verification/verify-component-state.md b/docs/site/docs/verification/verify-component-state.md index a2054ba17..0030137ba 100644 --- a/docs/site/docs/verification/verify-component-state.md +++ b/docs/site/docs/verification/verify-component-state.md @@ -5,9 +5,9 @@ title: Verifying the state of a component under test # Verifying the state of a component -The instance of a component under test is available through the property on the type. When using the 's `Render()` method, this is the type returned. +The instance of a component under test is available through the property on the type. When using the 's `Render()` method, this is the type returned. -In `.razor` based tests, using the 's method also returns an (as opposed to the method which returns the more simple ). +In `.razor` based tests, using the 's method also returns an (as opposed to the method which returns the more simple ). > [!NOTE] > Since inherits from , all the markup verification techniques covered on the page also apply to the type. diff --git a/src/bunit.generators/README.md b/src/bunit.generators/README.md index 201560c77..614fe5358 100644 --- a/src/bunit.generators/README.md +++ b/src/bunit.generators/README.md @@ -58,7 +58,7 @@ The general setup for the given component above looks like this: ```csharp namespace MyTest; -public class FeatureTests : TestContext +public class FeatureTests : BunitContext { [Fact] public void Test() diff --git a/src/bunit.template/template/BunitTestContext.cs b/src/bunit.template/template/BunitTestContext.cs deleted file mode 100644 index cdbaba27d..000000000 --- a/src/bunit.template/template/BunitTestContext.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Bunit; -#if (testFramework_nunit) -using NUnit.Framework; -#elif (testFramework_mstest) -using Microsoft.VisualStudio.TestTools.UnitTesting; -#endif - -namespace Company.BlazorTests1; - -/// -/// Test context wrapper for bUnit. -/// Read more about using here. -/// -public abstract class BunitTestContext : TestContextWrapper -{ -#if (testFramework_nunit) - [SetUp] -#elif (testFramework_mstest) - [TestInitialize] -#endif - public void Setup() => TestContext = new Bunit.TestContext(); - -#if (testFramework_nunit) - [TearDown] -#elif (testFramework_mstest) - [TestCleanup] -#endif - public void TearDown() => TestContext?.Dispose(); -} diff --git a/src/bunit.template/template/CounterCSharpTests.cs b/src/bunit.template/template/CounterCSharpTests.cs index ad32890d0..ad2168b12 100644 --- a/src/bunit.template/template/CounterCSharpTests.cs +++ b/src/bunit.template/template/CounterCSharpTests.cs @@ -5,12 +5,12 @@ namespace Company.BlazorTests1; /// Learn more at https://bunit.dev/docs/getting-started/writing-tests.html#creating-basic-tests-in-cs-files /// #if (testFramework_xunit) -public class CounterCSharpTests : TestContext +public class CounterCSharpTests : BunitContext #elif (testFramework_nunit) -public class CounterCSharpTests : BunitTestContext +public class CounterCSharpTests : BunitContext #elif (testFramework_mstest) [TestClass] -public class CounterCSharpTests : BunitTestContext +public class CounterCSharpTests : BunitContext #endif { #if (testFramework_xunit) diff --git a/src/bunit.template/template/CounterRazorTests.razor b/src/bunit.template/template/CounterRazorTests.razor index 7992eda2d..c762219f8 100644 --- a/src/bunit.template/template/CounterRazorTests.razor +++ b/src/bunit.template/template/CounterRazorTests.razor @@ -1,10 +1,10 @@ @*#if (testFramework_xunit)*@ -@inherits TestContext +@inherits BunitContext @*#elif (testFramework_nunit)*@ -@inherits BunitTestContext +@inherits BunitContext @*#elif (testFramework_mstest)*@ @attribute [TestClass] -@inherits BunitTestContext +@inherits BunitContext @*#endif*@ These tests are written entirely in razor and C# syntax. diff --git a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs index e4b4cee8e..c598e2320 100644 --- a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs +++ b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs @@ -295,7 +295,7 @@ public static void MarkupMatches(this INode actual, RenderFragment expected, str ArgumentNullException.ThrowIfNull(actual); ArgumentNullException.ThrowIfNull(expected); - var renderedFragment = actual.GetTestContext()?.RenderInsideRenderTree(expected) as RenderedFragment + var renderedFragment = actual.GetBunitContext()?.RenderInsideRenderTree(expected) as RenderedFragment ?? AdhocRenderRenderFragment(expected); MarkupMatches(actual, renderedFragment, userMessage); } @@ -314,7 +314,7 @@ public static void MarkupMatches(this INodeList actual, RenderFragment expected, ArgumentNullException.ThrowIfNull(actual); ArgumentNullException.ThrowIfNull(expected); - var renderedFragment = actual.GetTestContext()?.RenderInsideRenderTree(expected) as RenderedFragment + var renderedFragment = actual.GetBunitContext()?.RenderInsideRenderTree(expected) as RenderedFragment ?? AdhocRenderRenderFragment(expected); MarkupMatches(actual, renderedFragment, userMessage); } @@ -412,7 +412,7 @@ public static void MarkupMatches(this IEnumerable actual, IEnumerable< private static RenderedFragment AdhocRenderRenderFragment(this RenderFragment renderFragment) { - using var ctx = new TestContext(); + using var ctx = new BunitContext(); return ctx.RenderInsideRenderTree(renderFragment); } diff --git a/src/bunit/BunitContext.cs b/src/bunit/BunitContext.cs new file mode 100644 index 000000000..0b01f4c63 --- /dev/null +++ b/src/bunit/BunitContext.cs @@ -0,0 +1,190 @@ +using Bunit.Extensions; +using Bunit.Rendering; +using Microsoft.Extensions.Logging; + +namespace Bunit; + +/// +/// A test context is a factory that makes it possible to create components under tests. +/// +public partial class BunitContext : IDisposable, IAsyncDisposable +{ + private bool disposed; + private BunitRenderer? bunitRenderer; + + /// + /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . + /// + /// The default is 1 second. + public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); + + /// + /// Gets the renderer used by the test context. + /// + public BunitRenderer Renderer => bunitRenderer ??= CreateRenderer(); + + /// + /// Gets bUnits JSInterop, that allows setting up handlers for invocations + /// that components under tests will issue during testing. It also makes it possible to verify that the invocations has happened as expected. + /// + public BunitJSInterop JSInterop { get; } = new BunitJSInterop(); + + /// + /// Gets the service collection and service provider that is used when a + /// component is rendered by the test context. + /// + public TestServiceProvider Services { get; } + + /// + /// Gets the that all components rendered with the + /// Render<TComponent>() methods, are rendered inside. + /// + /// + /// Use this to add default layout- or root-components which a component under test + /// should be rendered under. + /// + public RootRenderTree RenderTree { get; } = new(); + + /// + /// Gets the . Factories added to it + /// will be used to create components during testing, starting with the last added + /// factory. If no factories in the collection can create a requested component, + /// then the default Blazor factory is used. + /// + public ComponentFactoryCollection ComponentFactories { get; } = new(); + + /// + /// Initializes a new instance of the class. + /// + public BunitContext() + { + Services = new TestServiceProvider(); + Services.AddSingleton(_ => ComponentFactories); + Services.AddDefaultBunitContextServices(this, JSInterop); + } + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + public async ValueTask DisposeAsync() + { + await DisposeAsyncCore(); + + Dispose(disposing: false); + GC.SuppressFinalize(this); + } + + /// + /// Disposes of the test context resources that are asynchronous, in particular it disposes the + /// service provider.s + /// + protected virtual async ValueTask DisposeAsyncCore() + { + if (disposed) + return; + + disposed = true; + + // Ensure the renderer is disposed before all others, + // otherwise a render cycle may be ongoing and try to access + // the service provider to perform operations. + if (bunitRenderer is not null) + { + await bunitRenderer.DisposeAsync(); + } + + await Services.DisposeAsync(); + } + + /// + /// Disposes of the test context resources, in particular it disposes the + /// service provider. + /// + /// + /// The disposing parameter should be false when called from a finalizer, and true when called from the + /// method. In other words, it is true when deterministically called and false when non-deterministically called. + /// + /// Set to true if called from , false if called from a finalizer.f. + protected virtual void Dispose(bool disposing) + { + if (disposed || !disposing) + return; + + disposed = true; + + // Ensure the renderer is disposed before all others, + // otherwise a render cycle may be ongoing and try to access + // the service provider to perform operations. + bunitRenderer?.Dispose(); + + // The service provider should dispose of any + // disposable object it has created, when it is disposed. + Services.Dispose(); + } + + /// + /// Disposes all components rendered via this . + /// + public void DisposeComponents() + { + Renderer.DisposeComponents(); + } + + /// + /// Instantiates and performs a first render of a component of type . + /// + /// Type of the component to render. + /// The ComponentParameterBuilder action to add type safe parameters to pass to the component when it is rendered. + /// The rendered . + public virtual RenderedComponent Render(Action>? parameterBuilder = null) + where TComponent : IComponent + { + var renderFragment = new ComponentParameterCollectionBuilder(parameterBuilder) + .Build() + .ToRenderFragment(); + + return Render(renderFragment); + } + + /// + /// Renders the and returns the first in the resulting render tree. + /// + /// + /// Calling this method is equivalent to calling Render(renderFragment).FindComponent<TComponent>(). + /// + /// The type of component to find in the render tree. + /// The render fragment to render. + /// The . + public virtual RenderedComponent Render(RenderFragment renderFragment) + where TComponent : IComponent + => this.RenderInsideRenderTree(renderFragment); + + /// + /// Renders the and returns it as a . + /// + /// The render fragment to render. + /// The . + public virtual RenderedFragment Render(RenderFragment renderFragment) + => this.RenderInsideRenderTree(renderFragment); + + /// + /// Dummy method required to allow Blazor's compiler to generate + /// C# from .razor files. + /// + protected virtual void BuildRenderTree(RenderTreeBuilder builder) { } + + private BunitRenderer CreateRenderer() + { + var logger = Services.GetRequiredService(); + + var componentActivator = Services.GetService(); + return componentActivator is null + ? new BunitRenderer(Services, logger) + : new BunitRenderer(Services, logger, componentActivator); + } +} diff --git a/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs b/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs index 3e3ebe461..01f64dd9e 100644 --- a/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs +++ b/src/bunit/ComponentFactories/InstanceComponentFactory{TComponent}.cs @@ -18,7 +18,7 @@ public IComponent Create(Type componentType) { throw new InvalidOperationException( $"The instance object passed to the" + - $"{nameof(TestContext.ComponentFactories)}.{nameof(ComponentFactoryCollectionExtensions.Add)}<{typeof(TComponent).Name}>(instance) method can only be used to replace " + + $"{nameof(BunitContext.ComponentFactories)}.{nameof(ComponentFactoryCollectionExtensions.Add)}<{typeof(TComponent).Name}>(instance) method can only be used to replace " + $"one {typeof(TComponent)} component in the render tree."); } diff --git a/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs index 7d75c7f6f..d5dc40768 100644 --- a/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs +++ b/src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs @@ -62,7 +62,7 @@ public static Task TriggerEventAsync(this IElement element, string eventName, Ev ArgumentNullException.ThrowIfNull(element); ArgumentNullException.ThrowIfNull(eventName); - var renderer = element.GetTestContext()?.Renderer + var renderer = element.GetBunitContext()?.Renderer ?? throw new InvalidOperationException($"Blazor events can only be raised on elements rendered with the Blazor test renderer '{nameof(BunitRenderer)}'."); // TriggerEventsAsync will traverse the DOM tree to find diff --git a/src/bunit/Extensions/Internal/AngleSharpExtensions.cs b/src/bunit/Extensions/Internal/AngleSharpExtensions.cs index a98d1830a..bc706cb04 100644 --- a/src/bunit/Extensions/Internal/AngleSharpExtensions.cs +++ b/src/bunit/Extensions/Internal/AngleSharpExtensions.cs @@ -61,23 +61,23 @@ public static HtmlComparer GetHtmlComparer(this INodeList nodes) } /// - /// Gets the stored in the s + /// Gets the stored in the s /// owning context, if one is available. /// - /// The or null if not found. - public static TestContext? GetTestContext(this INode? node) + /// The or null if not found. + public static BunitContext? GetBunitContext(this INode? node) { - return node?.Owner?.Context.GetService(); + return node?.Owner?.Context.GetService(); } /// - /// Gets the stored in the s + /// Gets the stored in the s /// owning context, if one is available. /// - /// The or null if not found. - public static TestContext? GetTestContext(this INodeList nodes) + /// The or null if not found. + public static BunitContext? GetBunitContext(this INodeList nodes) { - return nodes?.Length > 0 ? nodes[0].GetTestContext() : null; + return nodes?.Length > 0 ? nodes[0].GetBunitContext() : null; } /// diff --git a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs index b231e4710..c02f49e8e 100644 --- a/src/bunit/Extensions/RenderedComponentRenderExtensions.cs +++ b/src/bunit/Extensions/RenderedComponentRenderExtensions.cs @@ -18,7 +18,7 @@ public static void Render(this RenderedComponent rendere { ArgumentNullException.ThrowIfNull(renderedComponent); - var renderer = renderedComponent.Services.GetRequiredService().Renderer; + var renderer = renderedComponent.Services.GetRequiredService().Renderer; try { diff --git a/src/bunit/Extensions/RenderedFragmentExtensions.cs b/src/bunit/Extensions/RenderedFragmentExtensions.cs index e2f6d0070..2caf291a5 100644 --- a/src/bunit/Extensions/RenderedFragmentExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentExtensions.cs @@ -55,7 +55,7 @@ public static RenderedComponent FindComponent(this Rende { ArgumentNullException.ThrowIfNull(renderedFragment); - var renderer = renderedFragment.Services.GetRequiredService().Renderer; + var renderer = renderedFragment.Services.GetRequiredService().Renderer; return renderer.FindComponent(renderedFragment); } @@ -70,7 +70,7 @@ public static IReadOnlyList> FindComponents().Renderer; + var renderer = renderedFragment.Services.GetRequiredService().Renderer; var components = renderer.FindComponents(renderedFragment); return components.OfType>().ToArray(); diff --git a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs index cac702a71..99dac28f8 100644 --- a/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs +++ b/src/bunit/Extensions/RenderedFragmentInvokeAsyncExtensions.cs @@ -19,7 +19,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Action wo return renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); @@ -37,7 +37,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Func() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); @@ -55,7 +55,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Fun return renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); @@ -73,7 +73,7 @@ public static Task InvokeAsync(this RenderedFragment renderedFragment, Fun return renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer .Dispatcher .InvokeAsync(workItem); diff --git a/src/bunit/Extensions/TestContextRenderExtensions.cs b/src/bunit/Extensions/TestContextRenderExtensions.cs index d2d369970..2d91e947c 100644 --- a/src/bunit/Extensions/TestContextRenderExtensions.cs +++ b/src/bunit/Extensions/TestContextRenderExtensions.cs @@ -3,43 +3,43 @@ namespace Bunit.Extensions; /// -/// Extensions methods for types. +/// Extensions methods for types. /// -public static class TestContextRenderExtensions +public static class BunitContextRenderExtensions { /// - /// Renders a component, declared in the , inside the . + /// Renders a component, declared in the , inside the . /// /// The type of component to render. - /// Test context to use to render with. + /// Test context to use to render with. /// The that contains a declaration of the component. /// A . - public static RenderedComponent RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) + public static RenderedComponent RenderInsideRenderTree(this BunitContext bunitContext, RenderFragment renderFragment) where TComponent : IComponent { - ArgumentNullException.ThrowIfNull(testContext); + ArgumentNullException.ThrowIfNull(bunitContext); - var baseResult = RenderInsideRenderTree(testContext, renderFragment); - return testContext.Renderer.FindComponent(baseResult); + var baseResult = RenderInsideRenderTree(bunitContext, renderFragment); + return bunitContext.Renderer.FindComponent(baseResult); } /// - /// Renders a fragment, declared in the , inside the . + /// Renders a fragment, declared in the , inside the . /// - /// Test context to use to render with. + /// Test context to use to render with. /// The to render. /// A . - public static RenderedFragment RenderInsideRenderTree(this TestContext testContext, RenderFragment renderFragment) + public static RenderedFragment RenderInsideRenderTree(this BunitContext bunitContext, RenderFragment renderFragment) { - ArgumentNullException.ThrowIfNull(testContext); + ArgumentNullException.ThrowIfNull(bunitContext); // Wrap fragment in a FragmentContainer so the start of the test supplied // razor fragment can be found after, and then wrap in any layout components // added to the test context. var wrappedInFragmentContainer = FragmentContainer.Wrap(renderFragment); - var wrappedInRenderTree = testContext.RenderTree.Wrap(wrappedInFragmentContainer); - var resultBase = testContext.Renderer.RenderFragment(wrappedInRenderTree); + var wrappedInRenderTree = bunitContext.RenderTree.Wrap(wrappedInFragmentContainer); + var resultBase = bunitContext.Renderer.RenderFragment(wrappedInRenderTree); - return testContext.Renderer.FindComponent(resultBase); + return bunitContext.Renderer.FindComponent(resultBase); } } diff --git a/src/bunit/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/TestServiceProviderExtensions.cs index d40a08350..baa029fa7 100644 --- a/src/bunit/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit/Extensions/TestServiceProviderExtensions.cs @@ -15,12 +15,12 @@ namespace Bunit.Extensions; public static class TestServiceProviderExtensions { /// - /// Registers the default services required by the web . + /// Registers the default services required by the web . /// - public static IServiceCollection AddDefaultTestContextServices(this IServiceCollection services, TestContext testContext, BunitJSInterop jsInterop) + public static IServiceCollection AddDefaultBunitContextServices(this IServiceCollection services, BunitContext bunitContext, BunitJSInterop jsInterop) { ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(testContext); + ArgumentNullException.ThrowIfNull(bunitContext); ArgumentNullException.ThrowIfNull(jsInterop); // Placeholders and defaults for common Blazor services @@ -47,7 +47,7 @@ public static IServiceCollection AddDefaultTestContextServices(this IServiceColl services.AddSupplyValueFromQueryProvider(); // bUnit specific services - services.AddSingleton(testContext); + services.AddSingleton(bunitContext); services.AddSingleton(); services.AddSingleton(); diff --git a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs index feee65844..cf025325d 100644 --- a/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs +++ b/src/bunit/Extensions/WaitForHelpers/WaitForHelper.cs @@ -56,7 +56,7 @@ protected WaitForHelper( logger = renderedFragment.Services.CreateLogger>(); renderer = renderedFragment .Services - .GetRequiredService() + .GetRequiredService() .Renderer; checkPassedCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); timer = new Timer(_ => @@ -198,6 +198,6 @@ private static TimeSpan GetRuntimeTimeout(TimeSpan? timeout) { return Debugger.IsAttached ? Timeout.InfiniteTimeSpan - : timeout ?? TestContext.DefaultWaitTimeout; + : timeout ?? BunitContext.DefaultWaitTimeout; } } diff --git a/src/bunit/JSInterop/JSRuntimeUnhandledInvocationException.cs b/src/bunit/JSInterop/JSRuntimeUnhandledInvocationException.cs index 95fcc126f..6735c432e 100644 --- a/src/bunit/JSInterop/JSRuntimeUnhandledInvocationException.cs +++ b/src/bunit/JSInterop/JSRuntimeUnhandledInvocationException.cs @@ -79,7 +79,7 @@ private static string CreateErrorMessage(JSRuntimeInvocation invocation) sb.AppendLine(); sb.AppendLine("The setup methods are available on an instance of the BunitJSInterop or"); sb.AppendLine("BunitJSModuleInterop type. The standard BunitJSInterop is available"); - sb.AppendLine("through the TestContext.JSInterop property, and a BunitJSModuleInterop"); + sb.AppendLine("through the BunitContext.JSInterop property, and a BunitJSModuleInterop"); sb.AppendLine("instance is returned from calling SetupModule on a BunitJSInterop instance."); return sb.ToString(); } diff --git a/src/bunit/Rendering/BunitComponentActivator.cs b/src/bunit/Rendering/BunitComponentActivator.cs index 426b4da24..8b8a3876d 100644 --- a/src/bunit/Rendering/BunitComponentActivator.cs +++ b/src/bunit/Rendering/BunitComponentActivator.cs @@ -19,7 +19,7 @@ public IComponent CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessed } // The FragmentContainer is a bUnit component added to the - // render tree to separate the components from the TestContext.RenderTree + // render tree to separate the components from the BunitContext.RenderTree // and the components in the render fragment being rendered. // It should never be replaced by another component, as // this would break bUnits ability to detect the start diff --git a/src/bunit/Rendering/BunitHtmlParser.cs b/src/bunit/Rendering/BunitHtmlParser.cs index 261c8a5ba..4ed59cbf6 100644 --- a/src/bunit/Rendering/BunitHtmlParser.cs +++ b/src/bunit/Rendering/BunitHtmlParser.cs @@ -34,11 +34,11 @@ public BunitHtmlParser() /// Initializes a new instance of the class /// with a AngleSharp context registered. /// - public BunitHtmlParser(HtmlComparer htmlComparer, TestContext testContext) + public BunitHtmlParser(HtmlComparer htmlComparer, BunitContext bunitContext) : this(Configuration.Default.WithCss() .With(htmlComparer ?? throw new ArgumentNullException(nameof(htmlComparer))) - .With(testContext ?? throw new ArgumentNullException(nameof(testContext))) - .With(testContext.Renderer)) + .With(bunitContext ?? throw new ArgumentNullException(nameof(bunitContext))) + .With(bunitContext.Renderer)) { } private BunitHtmlParser(IConfiguration angleSharpConfiguration) diff --git a/src/bunit/TestContext.cs b/src/bunit/TestContext.cs index 693b7d591..f92082b22 100644 --- a/src/bunit/TestContext.cs +++ b/src/bunit/TestContext.cs @@ -1,190 +1,7 @@ -using Bunit.Extensions; -using Bunit.Rendering; -using Microsoft.Extensions.Logging; - namespace Bunit; -/// -/// A test context is a factory that makes it possible to create components under tests. -/// -public partial class TestContext : IDisposable, IAsyncDisposable +/// +[Obsolete($"Use {nameof(BunitContext)} instead. BunitContext will be removed in a future release.", false, UrlFormat = "https://bunit.dev/docs/migration")] +public class TestContext : BunitContext { - private bool disposed; - private BunitRenderer? bunitRenderer; - - /// - /// Gets or sets the default wait timeout used by "WaitFor" operations, i.e. . - /// - /// The default is 1 second. - public static TimeSpan DefaultWaitTimeout { get; set; } = TimeSpan.FromSeconds(1); - - /// - /// Gets the renderer used by the test context. - /// - public BunitRenderer Renderer => bunitRenderer ??= CreateRenderer(); - - /// - /// Gets bUnits JSInterop, that allows setting up handlers for invocations - /// that components under tests will issue during testing. It also makes it possible to verify that the invocations has happened as expected. - /// - public BunitJSInterop JSInterop { get; } = new BunitJSInterop(); - - /// - /// Gets the service collection and service provider that is used when a - /// component is rendered by the test context. - /// - public TestServiceProvider Services { get; } - - /// - /// Gets the that all components rendered with the - /// Render<TComponent>() methods, are rendered inside. - /// - /// - /// Use this to add default layout- or root-components which a component under test - /// should be rendered under. - /// - public RootRenderTree RenderTree { get; } = new(); - - /// - /// Gets the . Factories added to it - /// will be used to create components during testing, starting with the last added - /// factory. If no factories in the collection can create a requested component, - /// then the default Blazor factory is used. - /// - public ComponentFactoryCollection ComponentFactories { get; } = new(); - - /// - /// Initializes a new instance of the class. - /// - public TestContext() - { - Services = new TestServiceProvider(); - Services.AddSingleton(_ => ComponentFactories); - Services.AddDefaultTestContextServices(this, JSInterop); - } - - /// - public void Dispose() - { - Dispose(disposing: true); - GC.SuppressFinalize(this); - } - - /// - public async ValueTask DisposeAsync() - { - await DisposeAsyncCore(); - - Dispose(disposing: false); - GC.SuppressFinalize(this); - } - - /// - /// Disposes of the test context resources that are asynchronous, in particular it disposes the - /// service provider.s - /// - protected virtual async ValueTask DisposeAsyncCore() - { - if (disposed) - return; - - disposed = true; - - // Ensure the renderer is disposed before all others, - // otherwise a render cycle may be ongoing and try to access - // the service provider to perform operations. - if (bunitRenderer is not null) - { - await bunitRenderer.DisposeAsync(); - } - - await Services.DisposeAsync(); - } - - /// - /// Disposes of the test context resources, in particular it disposes the - /// service provider. - /// - /// - /// The disposing parameter should be false when called from a finalizer, and true when called from the - /// method. In other words, it is true when deterministically called and false when non-deterministically called. - /// - /// Set to true if called from , false if called from a finalizer.f. - protected virtual void Dispose(bool disposing) - { - if (disposed || !disposing) - return; - - disposed = true; - - // Ensure the renderer is disposed before all others, - // otherwise a render cycle may be ongoing and try to access - // the service provider to perform operations. - bunitRenderer?.Dispose(); - - // The service provider should dispose of any - // disposable object it has created, when it is disposed. - Services.Dispose(); - } - - /// - /// Disposes all components rendered via this . - /// - public void DisposeComponents() - { - Renderer.DisposeComponents(); - } - - /// - /// Instantiates and performs a first render of a component of type . - /// - /// Type of the component to render. - /// The ComponentParameterBuilder action to add type safe parameters to pass to the component when it is rendered. - /// The rendered . - public virtual RenderedComponent Render(Action>? parameterBuilder = null) - where TComponent : IComponent - { - var renderFragment = new ComponentParameterCollectionBuilder(parameterBuilder) - .Build() - .ToRenderFragment(); - - return Render(renderFragment); - } - - /// - /// Renders the and returns the first in the resulting render tree. - /// - /// - /// Calling this method is equivalent to calling Render(renderFragment).FindComponent<TComponent>(). - /// - /// The type of component to find in the render tree. - /// The render fragment to render. - /// The . - public virtual RenderedComponent Render(RenderFragment renderFragment) - where TComponent : IComponent - => this.RenderInsideRenderTree(renderFragment); - - /// - /// Renders the and returns it as a . - /// - /// The render fragment to render. - /// The . - public virtual RenderedFragment Render(RenderFragment renderFragment) - => this.RenderInsideRenderTree(renderFragment); - - /// - /// Dummy method required to allow Blazor's compiler to generate - /// C# from .razor files. - /// - protected virtual void BuildRenderTree(RenderTreeBuilder builder) { } - - private BunitRenderer CreateRenderer() - { - var logger = Services.GetRequiredService(); - - var componentActivator = Services.GetService(); - return componentActivator is null - ? new BunitRenderer(Services, logger) - : new BunitRenderer(Services, logger, componentActivator); - } } diff --git a/src/bunit/TestContextWrapper.cs b/src/bunit/TestContextWrapper.cs deleted file mode 100644 index 8fbbf14e7..000000000 --- a/src/bunit/TestContextWrapper.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Bunit.Rendering; - -namespace Bunit; - -/// -/// Represents a class that wraps a . Useful for -/// simplifying writing tests in NUnit and MSTest, which cannot -/// inherit directly from . -/// -public abstract class TestContextWrapper -{ - /// - /// Gets an instance of the wrapped , if any. - /// - protected virtual TestContext? TestContext { get; set; } - - /// - /// Gets the renderer used by the test context. - /// - public BunitRenderer Renderer => TestContext?.Renderer ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Gets the service collection and service provider that is used when a - /// component is rendered by the test context. - /// - public TestServiceProvider Services => TestContext?.Services ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Gets the service collection and service provider that is used when a - /// component is rendered by the test context. - /// - public RootRenderTree RenderTree => TestContext?.RenderTree ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Gets bUnits JSInterop, that allows setting up handlers for invocations - /// that components under tests will issue during testing. It also makes it possible to verify that the invocations has happened as expected. - /// - public BunitJSInterop JSInterop => TestContext?.JSInterop ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Instantiates and performs a first render of a component of type . - /// - /// Type of the component to render. - /// The ComponentParameterBuilder action to add type safe parameters to pass to the component when it is rendered. - /// The rendered . - public virtual RenderedComponent Render(Action>? parameterBuilder = null) - where TComponent : IComponent - => TestContext?.Render(parameterBuilder) ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Renders the and returns the first in the resulting render tree. - /// - /// - /// Calling this method is equivalent to calling Render(renderFragment).FindComponent<TComponent>(). - /// - /// The type of component to find in the render tree. - /// The render fragment to render. - /// The . - public virtual RenderedComponent Render(RenderFragment renderFragment) - where TComponent : IComponent - => TestContext?.Render(renderFragment) ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Renders the and returns it as a . - /// - /// The render fragment to render. - /// The . - public virtual RenderedFragment Render(RenderFragment renderFragment) - => TestContext?.Render(renderFragment) ?? throw new InvalidOperationException("The TestContext has not been initialized."); - - /// - /// Disposes all components rendered via this . - /// - public virtual void DisposeComponents() => TestContext?.DisposeComponents(); - - /// - /// Dummy method required to allow Blazor's compiler to generate - /// C# from .razor files. - /// - protected virtual void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) { } -} diff --git a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs index 9d86fc4f0..738b5abb8 100644 --- a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs @@ -4,7 +4,7 @@ namespace Bunit; -public partial class TestContext +public partial class BunitContext { /// /// Adds the appropriate Blazor authentication and authorization services to the to enable diff --git a/src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs b/src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs index 3598769f2..0cb1c1644 100644 --- a/src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs +++ b/src/bunit/TestDoubles/Authorization/MissingBunitAuthorizationException.cs @@ -2,7 +2,7 @@ namespace Bunit.TestDoubles; /// /// Exception used to indicate that the bunit authorization services are required by a test -/// but provided in TestContext.Services. +/// but provided in BunitContext.Services. /// [Serializable] public sealed class MissingBunitAuthorizationException : Exception @@ -18,7 +18,7 @@ public sealed class MissingBunitAuthorizationException : Exception /// /// The service being used. public MissingBunitAuthorizationException(string serviceName) - : base($"This test requires {serviceName} to be supplied, because the component under test uses authentication/authorization during the test. You can fix this by calling TestContext.Services.AddAuthorization with appropriate values. More information can be found in the documentation.") + : base($"This test requires {serviceName} to be supplied, because the component under test uses authentication/authorization during the test. You can fix this by calling BunitContext.Services.AddAuthorization with appropriate values. More information can be found in the documentation.") { ServiceName = serviceName; HelpLink = "https://bunit.egilhansen.com/docs/test-doubles/bunit-auth"; diff --git a/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs b/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs index 171c51f62..d9bad680c 100644 --- a/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs +++ b/src/bunit/TestDoubles/NavigationManager/BunitNavigationManager.cs @@ -12,7 +12,7 @@ namespace Bunit.TestDoubles; [DebuggerDisplay("Current Uri: {Uri}, History Count: {History.Count}")] public sealed class BunitNavigationManager : NavigationManager { - private readonly TestContext testContext; + private readonly BunitContext bunitContext; private readonly Stack history = new(); /// @@ -28,9 +28,9 @@ public sealed class BunitNavigationManager : NavigationManager /// Initializes a new instance of the class. /// [SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", Justification = "By design. Bunit navigation manager defaults to local host as base URI.")] - public BunitNavigationManager(TestContext testContext) + public BunitNavigationManager(BunitContext bunitContext) { - this.testContext = testContext; + this.bunitContext = bunitContext; Initialize("http://localhost/", "http://localhost/"); } @@ -51,7 +51,7 @@ protected override void NavigateToCore(string uri, NavigationOptions options) history.Pop(); HistoryEntryState = options.ForceLoad ? null : options.HistoryEntryState; - testContext.Renderer.Dispatcher.InvokeAsync(async () => + bunitContext.Renderer.Dispatcher.InvokeAsync(async () => { Uri = absoluteUri.OriginalString; diff --git a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs index 1209e5231..73ea41590 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs @@ -27,7 +27,7 @@ internal BunitPersistentComponentState(IServiceProvider services) { store = new BunitPersistentComponentStateStore(); manager = new Lazy(() => services.GetRequiredService()); - renderer = new Lazy(() => services.GetRequiredService().Renderer); + renderer = new Lazy(() => services.GetRequiredService().Renderer); } /// @@ -36,7 +36,7 @@ internal BunitPersistentComponentState(IServiceProvider services) /// component persistence. /// /// - /// Only call this method after all services has been registered with the . + /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// @@ -50,7 +50,7 @@ public void TriggerOnPersisting() /// Persists under the given in the store. /// /// - /// Only call this method after all services has been registered with the . + /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// @@ -70,7 +70,7 @@ public void Persist(string key, TValue instance) /// When the key is present, the state is successfully returned via . /// /// - /// Only call this method after all services has been registered with the . + /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the /// from the , which means no other services can be registered after this point. /// diff --git a/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs b/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs index b545938b9..77197d624 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/TestContextExtensions.cs @@ -3,10 +3,10 @@ namespace Bunit; -public partial class TestContext +public partial class BunitContext { /// - /// Adds and returns a to the services of this . + /// Adds and returns a to the services of this . /// /// The added . public BunitPersistentComponentState AddBunitPersistentComponentState() diff --git a/src/bunit/TestServiceProvider.cs b/src/bunit/TestServiceProvider.cs index 9e3054cbd..4afcb176d 100644 --- a/src/bunit/TestServiceProvider.cs +++ b/src/bunit/TestServiceProvider.cs @@ -250,7 +250,7 @@ private void CheckInitializedAndThrow() { throw new InvalidOperationException( "New services/implementations cannot be registered with the " + - "Services provider in a TestContext, after the first services has been retrieved " + + "Services provider in a BunitContext, after the first services has been retrieved " + "from it using e.g. the GetService or GetRequiredService methods. " + "This typically happens when a component is rendered, so make " + "sure all services are added before that."); diff --git a/tests/bunit.generators.tests/Web.Stub/AddStubGeneratorTests.cs b/tests/bunit.generators.tests/Web.Stub/AddStubGeneratorBunits.cs similarity index 97% rename from tests/bunit.generators.tests/Web.Stub/AddStubGeneratorTests.cs rename to tests/bunit.generators.tests/Web.Stub/AddStubGeneratorBunits.cs index d1dfcf60c..9d1293463 100644 --- a/tests/bunit.generators.tests/Web.Stub/AddStubGeneratorTests.cs +++ b/tests/bunit.generators.tests/Web.Stub/AddStubGeneratorBunits.cs @@ -2,7 +2,7 @@ namespace Bunit.Web.Stub; -public class AddStubGeneratorTests : TestContext +public class AddStubGeneratorBunits : BunitContext { [Fact] public void Stubbed_component_has_same_parameters() diff --git a/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsBunit.cs similarity index 97% rename from tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs rename to tests/bunit.tests/Asserting/CompareToDiffingExtensionsBunit.cs index cef1b5fc8..6bc12f401 100644 --- a/tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs +++ b/tests/bunit.tests/Asserting/CompareToDiffingExtensionsBunit.cs @@ -2,7 +2,7 @@ namespace Bunit; -public class CompareToDiffingExtensionsTest : TestContext +public class CompareToDiffingExtensionsBunit : BunitContext { /// /// Returns an array of arrays containing: diff --git a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsBunit.cs similarity index 99% rename from tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs rename to tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsBunit.cs index db305bafb..53a05e492 100644 --- a/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsTest.cs +++ b/tests/bunit.tests/Asserting/MarkupMatchesAssertExtensionsBunit.cs @@ -2,7 +2,7 @@ namespace Bunit.Asserting; -public partial class MarkupMatchesAssertExtensionsTest : TestContext +public partial class MarkupMatchesAssertExtensionsBunit : BunitContext { private const string ActualMarkup = "

    FOO

    "; private const string ExpectedMarkup = "
    BAR
    "; diff --git a/tests/bunit.tests/Asserting/MarkupMatchesTests.razor b/tests/bunit.tests/Asserting/MarkupMatchesTests.razor index 626e77807..d627134f7 100644 --- a/tests/bunit.tests/Asserting/MarkupMatchesTests.razor +++ b/tests/bunit.tests/Asserting/MarkupMatchesTests.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { diff --git a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs b/tests/bunit.tests/BlazorE2E/ComponentRenderingBunit.cs similarity index 99% rename from tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs rename to tests/bunit.tests/BlazorE2E/ComponentRenderingBunit.cs index 039ddac08..e381a0610 100644 --- a/tests/bunit.tests/BlazorE2E/ComponentRenderingTest.cs +++ b/tests/bunit.tests/BlazorE2E/ComponentRenderingBunit.cs @@ -13,14 +13,14 @@ namespace Bunit.BlazorE2E; /// /// This tests are based on the tests from the following AspNetCore tests class. /// The aim is to only modify the original tests to not use Selenium, and instead use the -/// . +/// . /// https://github.com/dotnet/aspnetcore/blob/master/src/Components/test/E2ETest/Tests/ComponentRenderingTest.cs. /// -public class ComponentRenderingTest : TestContext +public class ComponentRenderingBunit : BunitContext { - public ComponentRenderingTest(ITestOutputHelper outputHelper) + public ComponentRenderingBunit(ITestOutputHelper outputHelper) { - TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); + BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(outputHelper); JSInterop.Mode = JSRuntimeMode.Loose; } diff --git a/tests/bunit.tests/TestContextTest.cs b/tests/bunit.tests/BunitContextBunit.cs similarity index 96% rename from tests/bunit.tests/TestContextTest.cs rename to tests/bunit.tests/BunitContextBunit.cs index dc1dc39d9..19c4c630d 100644 --- a/tests/bunit.tests/TestContextTest.cs +++ b/tests/bunit.tests/BunitContextBunit.cs @@ -3,7 +3,7 @@ namespace Bunit; -public partial class TestContextTest : TestContext +public partial class BunitContextBunit : BunitContext { [Fact(DisplayName = "DisposeComponents disposes rendered components in parent to child order")] public void Test101() @@ -115,13 +115,13 @@ public void Test033() .ShouldBe("FOO"); } - [Fact(DisplayName = "Can raise events from markup rendered with TestContext")] + [Fact(DisplayName = "Can raise events from markup rendered with BunitContext")] public void Test040() { Should.NotThrow(() => Render().Find("button").Click()); } - [Fact(DisplayName = "TestContext should provide a default IErrorBoundaryLogger")] + [Fact(DisplayName = "BunitContext should provide a default IErrorBoundaryLogger")] public void Test001() { IErrorBoundaryLogger logger = Services.GetService(); @@ -210,7 +210,7 @@ public void Test203() public async Task Net5Test001() { AsyncDisposableService asyncDisposable; - await using (var sut = new TestContext()) + await using (var sut = new BunitContext()) { sut.Services.AddScoped(); asyncDisposable = sut.Services.GetService(); @@ -222,7 +222,7 @@ public async Task Net5Test001() public async Task Net5Test002() { AsyncDisposableService asyncDisposable; - await using (var sut = new TestContext()) + await using (var sut = new BunitContext()) { sut.Services.AddTransient(); asyncDisposable = sut.Services.GetService(); @@ -234,7 +234,7 @@ public async Task Net5Test002() public async Task Net5Test003() { AsyncDisposableService asyncDisposable; - await using (var sut = new TestContext()) + await using (var sut = new BunitContext()) { sut.Services.AddSingleton(); asyncDisposable = sut.Services.GetService(); diff --git a/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryBunit.cs similarity index 97% rename from tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryBunit.cs index 6a413bf19..6e8a3c955 100644 --- a/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/ConditionalComponentFactoryBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.ComponentFactories; -public class ConditionalComponentFactoryTest : TestContext +public class ConditionalComponentFactoryBunit : BunitContext { [Fact(DisplayName = "Add throws when factories is null")] public void Test001() diff --git a/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/GenericComponentFactoryBunit.cs similarity index 95% rename from tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/GenericComponentFactoryBunit.cs index 20bc753cd..a320e2018 100644 --- a/tests/bunit.tests/ComponentFactories/GenericComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/GenericComponentFactoryBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.ComponentFactories; -public class GenericComponentFactoryTest : TestContext +public class GenericComponentFactoryBunit : BunitContext { [Fact(DisplayName = "Add throws when factories is null")] public void Test001() diff --git a/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryBunit.cs similarity index 96% rename from tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/InstanceComponentFactoryBunit.cs index ad3b35105..177143c1c 100644 --- a/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/InstanceComponentFactoryBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.ComponentFactories; -public class InstanceComponentFactoryTest : TestContext +public class InstanceComponentFactoryBunit : BunitContext { [Fact(DisplayName = "Add throws when factories is null")] public void Test001() diff --git a/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/StubComponentFactoryBunit.cs similarity index 98% rename from tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/StubComponentFactoryBunit.cs index 9fdc34f94..37062583a 100644 --- a/tests/bunit.tests/ComponentFactories/StubComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/StubComponentFactoryBunit.cs @@ -2,7 +2,7 @@ namespace Bunit.ComponentFactories; -public class StubComponentFactoryTest : TestContext +public class StubComponentFactoryBunit : BunitContext { [Fact(DisplayName = "AddStub throws if predicate is null")] public void Test101() diff --git a/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs b/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryBunit.cs similarity index 95% rename from tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs rename to tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryBunit.cs index 34e114ec6..b39be3d80 100644 --- a/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryTest.cs +++ b/tests/bunit.tests/ComponentFactories/TypeBasedComponentFactoryBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.ComponentFactories; -public class TypeBasedComponentFactoryTest : TestContext +public class TypeBasedComponentFactoryBunit : BunitContext { [Fact(DisplayName = "Add throws when factories is null")] public void Test001() diff --git a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs b/tests/bunit.tests/ComponentParameterCollectionBuilderBunits.cs similarity index 99% rename from tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs rename to tests/bunit.tests/ComponentParameterCollectionBuilderBunits.cs index 82645f1b1..902bbd385 100644 --- a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.cs +++ b/tests/bunit.tests/ComponentParameterCollectionBuilderBunits.cs @@ -2,7 +2,7 @@ namespace Bunit; -public partial class ComponentParameterCollectionBuilderTests : TestContext +public partial class ComponentParameterCollectionBuilderBunits : BunitContext { private ComponentParameterCollectionBuilder Builder { get; } = new(); diff --git a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor b/tests/bunit.tests/ComponentParameterCollectionBuilderBunits.razor similarity index 97% rename from tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor rename to tests/bunit.tests/ComponentParameterCollectionBuilderBunits.razor index 69285be44..5110b423f 100644 --- a/tests/bunit.tests/ComponentParameterCollectionBuilderTests.razor +++ b/tests/bunit.tests/ComponentParameterCollectionBuilderBunits.razor @@ -1,4 +1,4 @@ -@inherits TestContext +@inherits BunitContext @code { [Fact(DisplayName = "Bind method should behave like bind-directive")] public async Task Test400() diff --git a/tests/bunit.tests/ComponentParameterCollectionTest.cs b/tests/bunit.tests/ComponentParameterCollectionBunit.cs similarity index 99% rename from tests/bunit.tests/ComponentParameterCollectionTest.cs rename to tests/bunit.tests/ComponentParameterCollectionBunit.cs index b091b364d..5d800a80c 100644 --- a/tests/bunit.tests/ComponentParameterCollectionTest.cs +++ b/tests/bunit.tests/ComponentParameterCollectionBunit.cs @@ -1,6 +1,6 @@ namespace Bunit; -public class ComponentParameterCollectionTest : TestContext +public class ComponentParameterCollectionBunit : BunitContext { private RenderedComponent RenderWithRenderFragment(RenderFragment renderFragment) { diff --git a/tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsBunit.cs similarity index 67% rename from tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsBunit.cs index f8110d62f..a97763be2 100644 --- a/tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/ClipboardEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class ClipboardEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class ClipboardEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public ClipboardEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public ClipboardEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsBunit.cs similarity index 80% rename from tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsBunit.cs index fcd3173c3..e14f4556a 100644 --- a/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/DetailsElementEventDispatcherExtensionsBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.EventDispatchExtensions; -public class DetailsElementEventDispatcherExtensionsTest : TestContext +public class DetailsElementEventDispatcherExtensionsBunit : BunitContext { [Fact(DisplayName = "Toggle raises ontoggle events")] public void Test200() diff --git a/tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsBunit.cs similarity index 77% rename from tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsBunit.cs index fbb6d7f95..2950f5fec 100644 --- a/tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/DragEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class DragEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class DragEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public DragEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public DragEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsBunit.cs similarity index 96% rename from tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsBunit.cs index 5a1f158f1..2160da1a8 100644 --- a/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/EventDispatchExtensionsBunit.cs @@ -2,14 +2,14 @@ namespace Bunit; -public abstract class EventDispatchExtensionsTest : TestContext +public abstract class EventDispatchExtensionsBunit : BunitContext where TEventArgs : EventArgs, new() { protected static readonly Type EventArgsType = typeof(TEventArgs); protected abstract string ElementName { get; } - protected EventDispatchExtensionsTest(ITestOutputHelper outputHelper) + protected EventDispatchExtensionsBunit(ITestOutputHelper outputHelper) { Services.AddXunitLogger(outputHelper); } diff --git a/tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsBunit.cs similarity index 68% rename from tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsBunit.cs index 6fc79f930..f5b9496ab 100644 --- a/tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/FocusEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class FocusEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class FocusEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public FocusEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public FocusEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsBunit.cs similarity index 98% rename from tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsBunit.cs index fe8b3b3f7..8dfd1328e 100644 --- a/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/GeneralEventDispatchExtensionsBunit.cs @@ -4,14 +4,14 @@ namespace Bunit; -public class GeneralEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class GeneralEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { protected override string ElementName => "p"; - public GeneralEventDispatchExtensionsTest(ITestOutputHelper outputHelper) + public GeneralEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { - TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); + BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); } [Theory(DisplayName = "General events are raised correctly through helpers")] diff --git a/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsBunit.cs similarity index 98% rename from tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsBunit.cs index 304c0b8ba..c4078e5be 100644 --- a/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/InputEventDispatchExtensionsBunit.cs @@ -1,6 +1,6 @@ namespace Bunit; -public class InputEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class InputEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { private static readonly string[] ExcludedMethodsFromGenericTests = new[] { "Change", "Input", "Submit" }; public static IEnumerable Helpers { get; } @@ -11,7 +11,7 @@ public class InputEventDispatchExtensionsTest : EventDispatchExtensionsTest "input"; - public InputEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public InputEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsBunit.cs similarity index 95% rename from tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsBunit.cs index e5c7c465d..068c91324 100644 --- a/tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/KeyboardEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class KeyboardEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class KeyboardEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public KeyboardEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public KeyboardEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsBunit.cs similarity index 65% rename from tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsBunit.cs index 3ee3153a5..efaa34ca7 100644 --- a/tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/MediaEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class MediaEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class MediaEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public MediaEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public MediaEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsBunit.cs similarity index 92% rename from tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsBunit.cs index 03d562b06..a4f577a5e 100644 --- a/tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/MouseEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class MouseEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class MouseEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public MouseEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public MouseEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsBunit.cs similarity index 80% rename from tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsBunit.cs index bc239a37d..c091a5810 100644 --- a/tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/PointerEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class PointerEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class PointerEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public PointerEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public PointerEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsBunit.cs similarity index 70% rename from tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsBunit.cs index ca63db4ed..237e00102 100644 --- a/tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/ProgressEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class ProgressEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class ProgressEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public ProgressEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public ProgressEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsBunit.cs similarity index 76% rename from tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsBunit.cs index b1e2ce8e2..7a9f206b9 100644 --- a/tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/TouchEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class TouchEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class TouchEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public TouchEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public TouchEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs b/tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsBunit.cs similarity index 80% rename from tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs rename to tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsBunit.cs index dbbb3ea17..630d48050 100644 --- a/tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsTest.cs +++ b/tests/bunit.tests/EventDispatchExtensions/WheelEventDispatchExtensionsBunit.cs @@ -1,8 +1,8 @@ namespace Bunit; -public class WheelEventDispatchExtensionsTest : EventDispatchExtensionsTest +public class WheelEventDispatchExtensionsBunit : EventDispatchExtensionsBunit { - public WheelEventDispatchExtensionsTest(ITestOutputHelper outputHelper) : base(outputHelper) + public WheelEventDispatchExtensionsBunit(ITestOutputHelper outputHelper) : base(outputHelper) { } diff --git a/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs b/tests/bunit.tests/Extensions/InputFile/InputFileBunits.cs similarity index 99% rename from tests/bunit.tests/Extensions/InputFile/InputFileTests.cs rename to tests/bunit.tests/Extensions/InputFile/InputFileBunits.cs index d379f0abe..56f7c0e35 100644 --- a/tests/bunit.tests/Extensions/InputFile/InputFileTests.cs +++ b/tests/bunit.tests/Extensions/InputFile/InputFileBunits.cs @@ -6,7 +6,7 @@ namespace Bunit.Extensions.InputFile; using InputFile = Microsoft.AspNetCore.Components.Forms.InputFile; -public class InputFileTests : TestContext +public class InputFileBunits : BunitContext { [Fact(DisplayName = "InputFile can upload a single string file")] public void Test001() diff --git a/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs b/tests/bunit.tests/Extensions/RefreshableQueryCollectionBunit.cs similarity index 96% rename from tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs rename to tests/bunit.tests/Extensions/RefreshableQueryCollectionBunit.cs index c26763f7a..c7d522981 100644 --- a/tests/bunit.tests/Extensions/RefreshableQueryCollectionTest.cs +++ b/tests/bunit.tests/Extensions/RefreshableQueryCollectionBunit.cs @@ -1,6 +1,6 @@ namespace Bunit; -public class RefreshableQueryCollectionTest : TestContext +public class RefreshableQueryCollectionBunit : BunitContext { [Fact(DisplayName = "When the query returns no elements, the collection is empty")] public void Test001() diff --git a/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs b/tests/bunit.tests/Extensions/RefreshingWrappedElementBunit.cs similarity index 97% rename from tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs rename to tests/bunit.tests/Extensions/RefreshingWrappedElementBunit.cs index 022b29bd4..048a812b9 100644 --- a/tests/bunit.tests/Extensions/RefreshingWrappedElementTest.cs +++ b/tests/bunit.tests/Extensions/RefreshingWrappedElementBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.Extensions; -public class RefreshingWrappedElementTest : TestContext +public class RefreshingWrappedElementBunit : BunitContext { [Fact(DisplayName = "Find() throws when element doesn't exist in DOM")] public void Test001() diff --git a/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs b/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsBunit.cs similarity index 84% rename from tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs rename to tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsBunit.cs index 1c829cea6..e0a29ea90 100644 --- a/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/RenderedComponentRenderExtensionsBunit.cs @@ -1,6 +1,6 @@ namespace Bunit; -public class RenderedComponentRenderExtensionsTest : TestContext +public class RenderedComponentRenderExtensionsBunit : BunitContext { [Fact(DisplayName = "Render rethrows exceptions from SetParameterAsync")] public void Test001() diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs index 68cb1f3fd..a984f08c2 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs @@ -2,13 +2,13 @@ namespace Bunit.Extensions.WaitForHelpers; -public class RenderedFragmentWaitForElementsHelperExtensionsAsyncTest : TestContext +public class RenderedFragmentWaitForElementsHelperExtensionsAsyncBunit : BunitContext { private readonly static TimeSpan WaitForTestTimeout = TimeSpan.FromMilliseconds(5); - public RenderedFragmentWaitForElementsHelperExtensionsAsyncTest(ITestOutputHelper testOutput) + public RenderedFragmentWaitForElementsHelperExtensionsAsyncBunit(ITestOutputHelper testOutput) { - TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); + BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(testOutput); } diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsBunit.cs similarity index 93% rename from tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs rename to tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsBunit.cs index 5608444a0..b472a9439 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForElementsHelperExtensionsBunit.cs @@ -2,13 +2,13 @@ namespace Bunit.Extensions.WaitForHelpers; -public class RenderedFragmentWaitForElementsHelperExtensionsTest : TestContext +public class RenderedFragmentWaitForElementsHelperExtensionsBunit : BunitContext { private readonly static TimeSpan WaitForTestTimeout = TimeSpan.FromMilliseconds(5); - public RenderedFragmentWaitForElementsHelperExtensionsTest(ITestOutputHelper testOutput) + public RenderedFragmentWaitForElementsHelperExtensionsBunit(ITestOutputHelper testOutput) { - TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); + BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(testOutput); } diff --git a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsBunit.cs similarity index 96% rename from tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs rename to tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsBunit.cs index 1d079114c..b63289a8f 100644 --- a/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsTest.cs +++ b/tests/bunit.tests/Extensions/WaitForHelpers/RenderedFragmentWaitForHelperExtensionsBunit.cs @@ -2,9 +2,9 @@ namespace Bunit.Extensions.WaitForHelpers; -public class RenderedFragmentWaitForHelperExtensionsTest : TestContext +public class RenderedFragmentWaitForHelperExtensionsBunit : BunitContext { - public RenderedFragmentWaitForHelperExtensionsTest(ITestOutputHelper testOutput) + public RenderedFragmentWaitForHelperExtensionsBunit(ITestOutputHelper testOutput) { Services.AddXunitLogger(testOutput); } diff --git a/tests/bunit.tests/JSInterop/BunitJSObjectReferenceTest.cs b/tests/bunit.tests/JSInterop/BunitJsObjectReferenceBunit.cs similarity index 99% rename from tests/bunit.tests/JSInterop/BunitJSObjectReferenceTest.cs rename to tests/bunit.tests/JSInterop/BunitJsObjectReferenceBunit.cs index 2bfe5efb1..1a36b3f84 100644 --- a/tests/bunit.tests/JSInterop/BunitJSObjectReferenceTest.cs +++ b/tests/bunit.tests/JSInterop/BunitJsObjectReferenceBunit.cs @@ -5,7 +5,7 @@ namespace Bunit.JSInterop; -public class BunitJSObjectReferenceTest : TestContext +public class BunitJsObjectReferenceBunit : BunitContext { private static readonly Type JSVoidResultType = typeof(Microsoft.JSInterop.Infrastructure.IJSVoidResult); diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerBunit.cs similarity index 95% rename from tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs rename to tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerBunit.cs index fd916a89d..6af74a347 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusAsyncInvocationHandlerBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.JSInterop.InvocationHandlers; -public class FocusAsyncInvocationHandlerTest : TestContext +public class FocusAsyncInvocationHandlerBunit : BunitContext { [Fact(DisplayName = "Can render components that calls FocusAsync")] public void Test001() diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerBunit.cs similarity index 96% rename from tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs rename to tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerBunit.cs index 6bcffec35..689e1fbc1 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/FocusOnNavigateHandlerBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.JSInterop.InvocationHandlers; -public class FocusOnNavigateHandlerTest : TestContext +public class FocusOnNavigateHandlerBunit : BunitContext { [Fact(DisplayName = "Can render components that calls FocusOnNavigate")] public void Test001() diff --git a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerBunit.cs similarity index 98% rename from tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs rename to tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerBunit.cs index 1522c4611..f7817663f 100644 --- a/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJSRuntimeInvocationHandlerTest.cs +++ b/tests/bunit.tests/JSInterop/InvocationHandlers/VirtualizeJsRuntimeInvocationHandlerBunit.cs @@ -2,7 +2,7 @@ namespace Bunit.JSInterop.ComponentSupport; -public class VirtualizeJSRuntimeInvocationHandlerTest : TestContext +public class VirtualizeJsRuntimeInvocationHandlerBunit : BunitContext { public static readonly IEnumerable ItemsInCollection = new object[][] { diff --git a/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs index e1c5a4ae9..1a7d6c9c6 100644 --- a/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs +++ b/tests/bunit.tests/JSInterop/JSRuntimeUnhandledInvocationExceptionTest.cs @@ -17,7 +17,7 @@ private static string CreateExpectedErrorMessage(string invocationMethod, string $"{suggestedSetup}{Environment.NewLine}{Environment.NewLine}" + $"The setup methods are available on an instance of the BunitJSInterop or{Environment.NewLine}" + $"BunitJSModuleInterop type. The standard BunitJSInterop is available{Environment.NewLine}" + - $"through the TestContext.JSInterop property, and a BunitJSModuleInterop{Environment.NewLine}" + + $"through the BunitContext.JSInterop property, and a BunitJSModuleInterop{Environment.NewLine}" + $"instance is returned from calling SetupModule on a BunitJSInterop instance.{Environment.NewLine}"; } @@ -292,7 +292,7 @@ public void Test035(string identifier) Assert.Equal(expectedErrorMessage, sut.Message); } - + [Theory(DisplayName = "Message prints correctly when trying to import an unconfigured module")] [AutoData] public void Test036(string moduleName) diff --git a/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs b/tests/bunit.tests/Rendering/BunitComponentActivatorBunit.cs similarity index 96% rename from tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs rename to tests/bunit.tests/Rendering/BunitComponentActivatorBunit.cs index 88332b291..9dbce8c60 100644 --- a/tests/bunit.tests/Rendering/BunitComponentActivatorTest.cs +++ b/tests/bunit.tests/Rendering/BunitComponentActivatorBunit.cs @@ -2,7 +2,7 @@ namespace Bunit.Rendering; -public class BunitComponentActivatorTest : TestContext +public class BunitComponentActivatorBunit : BunitContext { [Fact(DisplayName = "Default activator")] public void Test001() diff --git a/tests/bunit.tests/Rendering/BunitRendererTests.cs b/tests/bunit.tests/Rendering/BunitRendererBunits.cs similarity index 99% rename from tests/bunit.tests/Rendering/BunitRendererTests.cs rename to tests/bunit.tests/Rendering/BunitRendererBunits.cs index caf52697d..94af2bd9b 100644 --- a/tests/bunit.tests/Rendering/BunitRendererTests.cs +++ b/tests/bunit.tests/Rendering/BunitRendererBunits.cs @@ -3,9 +3,9 @@ namespace Bunit.Rendering; -public class BunitRendererTests : TestContext +public class BunitRendererBunits : BunitContext { - public BunitRendererTests(ITestOutputHelper outputHelper) + public BunitRendererBunits(ITestOutputHelper outputHelper) { DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(outputHelper); diff --git a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs b/tests/bunit.tests/Rendering/Internal/HtmlizerBunits.cs similarity index 98% rename from tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs rename to tests/bunit.tests/Rendering/Internal/HtmlizerBunits.cs index f9891fde9..af1d438cb 100644 --- a/tests/bunit.tests/Rendering/Internal/HtmlizerTests.cs +++ b/tests/bunit.tests/Rendering/Internal/HtmlizerBunits.cs @@ -1,6 +1,6 @@ namespace Bunit.Rendering.Internal; -public partial class HtmlizerTests : TestContext +public partial class HtmlizerBunits : BunitContext { [Theory(DisplayName = "Htmlizer correctly prefixed stopPropagation and preventDefault attributes")] [InlineData(false, true)] diff --git a/tests/bunit.tests/Rendering/RenderedComponentTest.cs b/tests/bunit.tests/Rendering/RenderedComponentBunit.cs similarity index 97% rename from tests/bunit.tests/Rendering/RenderedComponentTest.cs rename to tests/bunit.tests/Rendering/RenderedComponentBunit.cs index 3853e1f32..358194269 100644 --- a/tests/bunit.tests/Rendering/RenderedComponentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedComponentBunit.cs @@ -2,7 +2,7 @@ namespace Bunit; -public class RenderedComponentTest : TestContext +public class RenderedComponentBunit : BunitContext { [Fact(DisplayName = "Call to Render() results in a render of component")] public void Test001() diff --git a/tests/bunit.tests/Rendering/RenderedFragmentTest.cs b/tests/bunit.tests/Rendering/RenderedFragmentBunit.cs similarity index 97% rename from tests/bunit.tests/Rendering/RenderedFragmentTest.cs rename to tests/bunit.tests/Rendering/RenderedFragmentBunit.cs index bae1da34d..50fb73a7a 100644 --- a/tests/bunit.tests/Rendering/RenderedFragmentTest.cs +++ b/tests/bunit.tests/Rendering/RenderedFragmentBunit.cs @@ -2,9 +2,9 @@ namespace Bunit; -public class RenderedFragmentTest : TestContext +public class RenderedFragmentBunit : BunitContext { - public RenderedFragmentTest(ITestOutputHelper output) + public RenderedFragmentBunit(ITestOutputHelper output) { Services.AddXunitLogger(output); } diff --git a/tests/bunit.tests/Rendering/RootRenderTreeTest.cs b/tests/bunit.tests/Rendering/RootRenderTreeBunit.cs similarity index 99% rename from tests/bunit.tests/Rendering/RootRenderTreeTest.cs rename to tests/bunit.tests/Rendering/RootRenderTreeBunit.cs index 8276809d5..51629886f 100644 --- a/tests/bunit.tests/Rendering/RootRenderTreeTest.cs +++ b/tests/bunit.tests/Rendering/RootRenderTreeBunit.cs @@ -3,7 +3,7 @@ namespace Bunit; -public class RootRenderTreeTest : TestContext +public class RootRenderTreeBunit : BunitContext { [Fact(DisplayName = "Count returns number of component registrations added")] public void Test010() diff --git a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationBunit.cs similarity index 97% rename from tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs rename to tests/bunit.tests/TestDoubles/Authorization/AuthorizationBunit.cs index e64ab77c3..e71142db3 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/AuthorizationTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/AuthorizationBunit.cs @@ -2,11 +2,11 @@ namespace Bunit.TestDoubles.Authorization; -public class AuthorizationTest : TestContext +public class AuthorizationBunit : BunitContext { - public AuthorizationTest(ITestOutputHelper outputHelper) + public AuthorizationBunit(ITestOutputHelper outputHelper) { - TestContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); + BunitContext.DefaultWaitTimeout = TimeSpan.FromSeconds(30); Services.AddXunitLogger(outputHelper); } diff --git a/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs index 25b4d8e8e..b25d5e755 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationContextBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles.Authorization; -public class BunitAuthorizationContextBunit : TestContext +public class BunitAuthorizationContextBunit : BunitContext { [Fact(DisplayName = "Register Authorization services with unauthenticated user.")] public void Test003() diff --git a/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs index fcef20f4e..f16cb2519 100644 --- a/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs +++ b/tests/bunit.tests/TestDoubles/Authorization/BunitAuthorizationServiceTest.cs @@ -56,7 +56,7 @@ public async Task Test004() public async Task Test005() { // arrange - using var ctx = new TestContext(); + using var ctx = new BunitContext(); var authService = ctx.Services.GetRequiredService(); var requirements = Array.Empty(); @@ -72,7 +72,7 @@ public async Task Test005() public async Task Test006() { // arrange - using var ctx = new TestContext(); + using var ctx = new BunitContext(); var authService = ctx.Services.GetRequiredService(); // act diff --git a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerBunit.cs similarity index 91% rename from tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs rename to tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerBunit.cs index a44403380..b88a4ab0b 100644 --- a/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitSignOutSessionStateManagerBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles; -public class BunitSignOutSessionStateManagerTest : TestContext +public class BunitSignOutSessionStateManagerBunit : BunitContext { [Theory, AutoData] public void ShouldSignOut(string randomUserName) diff --git a/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs b/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentBunit.cs similarity index 92% rename from tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs rename to tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentBunit.cs index 2e92ebc32..84c4a46e3 100644 --- a/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentTest.cs +++ b/tests/bunit.tests/TestDoubles/BunitWebAssemblyHostEnvironmentBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles; -public class BunitWebAssemblyHostEnvironmentTest : TestContext +public class BunitWebAssemblyHostEnvironmentBunit : BunitContext { [Fact] public void ShouldSayHelloToDevelopers() diff --git a/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseBunit.cs similarity index 89% rename from tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs rename to tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseBunit.cs index 8caa8ebc3..1bd94428b 100644 --- a/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseTest.cs +++ b/tests/bunit.tests/TestDoubles/Components/ComponentDoubleBaseBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles.Components; -public class ComponentDoubleBaseTest : TestContext +public class ComponentDoubleBaseBunit : BunitContext { private sealed class ComponentDouble : ComponentDoubleBase where TComponent : IComponent diff --git a/tests/bunit.tests/TestDoubles/Components/StubTest.cs b/tests/bunit.tests/TestDoubles/Components/StubBunit.cs similarity index 95% rename from tests/bunit.tests/TestDoubles/Components/StubTest.cs rename to tests/bunit.tests/TestDoubles/Components/StubBunit.cs index b26296fa9..c1941498b 100644 --- a/tests/bunit.tests/TestDoubles/Components/StubTest.cs +++ b/tests/bunit.tests/TestDoubles/Components/StubBunit.cs @@ -1,6 +1,6 @@ namespace Bunit.TestDoubles.Components; -public class StubTest : TestContext +public class StubBunit : BunitContext { [Fact(DisplayName = "Stub renders nothing without a replacement template")] public void Test001() diff --git a/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs index 629da5514..c235d437a 100644 --- a/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs +++ b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationInterceptionTest.cs @@ -14,7 +14,7 @@ public void Test001() [Fact(DisplayName = "FakeNavigationInterception is registered as the default INavigationInterception")] public void Test002() { - using var ctx = new TestContext(); + using var ctx = new BunitContext(); ctx.Services.GetService() .ShouldBeOfType(); } diff --git a/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerBunit.cs similarity index 98% rename from tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs rename to tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerBunit.cs index 6b85552bc..3b5689b45 100644 --- a/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerTest.cs +++ b/tests/bunit.tests/TestDoubles/NavigationManager/BunitNavigationManagerBunit.cs @@ -5,12 +5,12 @@ namespace Bunit.TestDoubles; using static Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers; -public class BunitNavigationManagerTest : TestContext +public class BunitNavigationManagerBunit : BunitContext { private BunitNavigationManager CreateNavigationManager() => Services.GetRequiredService(); - [Fact(DisplayName = "TestContext.Services has NavigationManager registered by default as BunitNavigationManager")] + [Fact(DisplayName = "BunitContext.Services has NavigationManager registered by default as BunitNavigationManager")] public void Test001() { var nm = Services.GetService(); diff --git a/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs b/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateBunit.cs similarity index 93% rename from tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs rename to tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateBunit.cs index e25bfd14d..a5a059cfd 100644 --- a/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateTest.cs +++ b/tests/bunit.tests/TestDoubles/PersistentComponentState/BunitPersistentComponentStateBunit.cs @@ -1,8 +1,8 @@ namespace Bunit.TestDoubles; -public class BunitPersistentComponentStateTest : TestContext +public class BunitPersistentComponentStateBunit : BunitContext { - public BunitPersistentComponentStateTest(ITestOutputHelper outputHelper) + public BunitPersistentComponentStateBunit(ITestOutputHelper outputHelper) { Services.AddXunitLogger(outputHelper); } diff --git a/tests/bunit.tests/TestServiceProviderTest.cs b/tests/bunit.tests/TestServiceProviderTest.cs index 363fc1105..75facc538 100644 --- a/tests/bunit.tests/TestServiceProviderTest.cs +++ b/tests/bunit.tests/TestServiceProviderTest.cs @@ -173,7 +173,7 @@ public void Test025() public void Test030() { // Arrange - using var ctx = new TestContext(); + using var ctx = new BunitContext(); var fallbackServiceProvider = new ServiceCollection() .AddSingleton(new DummyService()) .BuildServiceProvider(); @@ -300,7 +300,7 @@ public void Test039() [Fact(DisplayName = "Should resolve keyed service from container")] public void Test040() { - using var ctx = new TestContext(); + using var ctx = new BunitContext(); ctx.Services.AddKeyedScoped("Key"); var cut = ctx.Render(); @@ -311,7 +311,7 @@ public void Test040() [Fact(DisplayName = "Should resolved keyed service from fallback service provider")] public void Test041() { - using var ctx = new TestContext(); + using var ctx = new BunitContext(); var fallbackCollection = new ServiceCollection(); fallbackCollection.AddKeyedScoped("Key"); ctx.Services.AddFallbackServiceProvider(fallbackCollection.BuildServiceProvider()); @@ -324,7 +324,7 @@ public void Test041() [Fact(DisplayName = "Throw an exception if required keyed service is not found")] public void Test042() { - using var ctx = new TestContext(); + using var ctx = new BunitContext(); Should.Throw(() => ctx.Render()); } From a73989f795adf14b953b9fc7410817c0d484bd4d Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 16:20:16 +0100 Subject: [PATCH 021/100] feat: Add Obsolete attribute for removed RenderComponent methods --- src/bunit/BunitContext.Obsoletes.cs | 24 ++++++++++++++++++++++++ src/bunit/bunit.csproj | 1 + 2 files changed, 25 insertions(+) create mode 100644 src/bunit/BunitContext.Obsoletes.cs diff --git a/src/bunit/BunitContext.Obsoletes.cs b/src/bunit/BunitContext.Obsoletes.cs new file mode 100644 index 000000000..bef3d21b5 --- /dev/null +++ b/src/bunit/BunitContext.Obsoletes.cs @@ -0,0 +1,24 @@ +namespace Bunit; + +public partial class BunitContext +{ + /// + /// Use instead. + /// + [Obsolete($"Use {nameof(Render)} instead.", true, UrlFormat = "https://bunit.dev/docs/migration")] + public RenderedComponent 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/migration")] + public RenderedComponent RenderComponent(Action>? parameterBuilder) + where TComponent : IComponent + { + throw new NotSupportedException($"Use {nameof(Render)}<{typeof(TComponent).Name}> instead."); + } +} diff --git a/src/bunit/bunit.csproj b/src/bunit/bunit.csproj index 4e0dc3cff..d15940429 100644 --- a/src/bunit/bunit.csproj +++ b/src/bunit/bunit.csproj @@ -1,6 +1,7 @@ net8.0;net9.0 + Bunit From bd66f3febb16522b8bd5d90f929ecc6e07c4f633 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 16:35:28 +0100 Subject: [PATCH 022/100] refactor: Move RenderInsideRenderTreeto BunitContext and make it private --- .../MarkupMatchesAssertExtensions.cs | 6 +-- src/bunit/BunitContext.cs | 32 ++++++++++++- .../Extensions/TestContextRenderExtensions.cs | 45 ------------------- 3 files changed, 34 insertions(+), 49 deletions(-) delete mode 100644 src/bunit/Extensions/TestContextRenderExtensions.cs diff --git a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs index c598e2320..61e3a4132 100644 --- a/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs +++ b/src/bunit/Asserting/MarkupMatchesAssertExtensions.cs @@ -295,7 +295,7 @@ public static void MarkupMatches(this INode actual, RenderFragment expected, str ArgumentNullException.ThrowIfNull(actual); ArgumentNullException.ThrowIfNull(expected); - var renderedFragment = actual.GetBunitContext()?.RenderInsideRenderTree(expected) as RenderedFragment + var renderedFragment = actual.GetBunitContext()?.Render(expected) ?? AdhocRenderRenderFragment(expected); MarkupMatches(actual, renderedFragment, userMessage); } @@ -314,7 +314,7 @@ public static void MarkupMatches(this INodeList actual, RenderFragment expected, ArgumentNullException.ThrowIfNull(actual); ArgumentNullException.ThrowIfNull(expected); - var renderedFragment = actual.GetBunitContext()?.RenderInsideRenderTree(expected) as RenderedFragment + var renderedFragment = actual.GetBunitContext()?.Render(expected) ?? AdhocRenderRenderFragment(expected); MarkupMatches(actual, renderedFragment, userMessage); } @@ -413,7 +413,7 @@ public static void MarkupMatches(this IEnumerable actual, IEnumerable< private static RenderedFragment AdhocRenderRenderFragment(this RenderFragment renderFragment) { using var ctx = new BunitContext(); - return ctx.RenderInsideRenderTree(renderFragment); + return ctx.Render(renderFragment); } private static INodeList ToNodeList(this string markup, BunitHtmlParser? htmlParser) diff --git a/src/bunit/BunitContext.cs b/src/bunit/BunitContext.cs index 0b01f4c63..1864e6c61 100644 --- a/src/bunit/BunitContext.cs +++ b/src/bunit/BunitContext.cs @@ -170,7 +170,7 @@ public virtual RenderedComponent Render(RenderFragment r /// The render fragment to render. /// The . public virtual RenderedFragment Render(RenderFragment renderFragment) - => this.RenderInsideRenderTree(renderFragment); + => RenderInsideRenderTree(renderFragment); /// /// Dummy method required to allow Blazor's compiler to generate @@ -187,4 +187,34 @@ private BunitRenderer CreateRenderer() ? new BunitRenderer(Services, logger) : new BunitRenderer(Services, logger, componentActivator); } + + /// + /// Renders a component, declared in the , inside the . + /// + /// The type of component to render. + /// The that contains a declaration of the component. + /// A . + private RenderedComponent RenderInsideRenderTree(RenderFragment renderFragment) + where TComponent : IComponent + { + var baseResult = RenderInsideRenderTree(renderFragment); + return Renderer.FindComponent(baseResult); + } + + /// + /// Renders a fragment, declared in the , inside the . + /// + /// The to render. + /// A . + private RenderedComponent RenderInsideRenderTree(RenderFragment renderFragment) + { + // Wrap fragment in a FragmentContainer so the start of the test supplied + // razor fragment can be found after, and then wrap in any layout components + // added to the test context. + var wrappedInFragmentContainer = FragmentContainer.Wrap(renderFragment); + var wrappedInRenderTree = RenderTree.Wrap(wrappedInFragmentContainer); + var resultBase = Renderer.RenderFragment(wrappedInRenderTree); + + return Renderer.FindComponent(resultBase); + } } diff --git a/src/bunit/Extensions/TestContextRenderExtensions.cs b/src/bunit/Extensions/TestContextRenderExtensions.cs deleted file mode 100644 index 2d91e947c..000000000 --- a/src/bunit/Extensions/TestContextRenderExtensions.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Bunit.Rendering; - -namespace Bunit.Extensions; - -/// -/// Extensions methods for types. -/// -public static class BunitContextRenderExtensions -{ - /// - /// Renders a component, declared in the , inside the . - /// - /// The type of component to render. - /// Test context to use to render with. - /// The that contains a declaration of the component. - /// A . - public static RenderedComponent RenderInsideRenderTree(this BunitContext bunitContext, RenderFragment renderFragment) - where TComponent : IComponent - { - ArgumentNullException.ThrowIfNull(bunitContext); - - var baseResult = RenderInsideRenderTree(bunitContext, renderFragment); - return bunitContext.Renderer.FindComponent(baseResult); - } - - /// - /// Renders a fragment, declared in the , inside the . - /// - /// Test context to use to render with. - /// The to render. - /// A . - public static RenderedFragment RenderInsideRenderTree(this BunitContext bunitContext, RenderFragment renderFragment) - { - ArgumentNullException.ThrowIfNull(bunitContext); - - // Wrap fragment in a FragmentContainer so the start of the test supplied - // razor fragment can be found after, and then wrap in any layout components - // added to the test context. - var wrappedInFragmentContainer = FragmentContainer.Wrap(renderFragment); - var wrappedInRenderTree = bunitContext.RenderTree.Wrap(wrappedInFragmentContainer); - var resultBase = bunitContext.Renderer.RenderFragment(wrappedInRenderTree); - - return bunitContext.Renderer.FindComponent(resultBase); - } -} From 25e3f5be18e6eb69d4735b1a64f30e1518f766eb Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 16:42:42 +0100 Subject: [PATCH 023/100] fix: Remove dotnet pack of non-existing packages --- .github/workflows/ci.yml | 2 -- .github/workflows/release.yml | 2 -- 2 files changed, 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5ad62e1dc..522e8009c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,8 +74,6 @@ jobs: # Create the NuGet package in the folder from the environment variable NuGetDirectory - run: | dotnet pack src/bunit/ -c Release --output ${{ env.NUGET_DIRECTORY }} -p:ContinuousIntegrationBuild=true -p:publicrelease=true - dotnet pack src/bunit.core/ -c Release --output ${{ env.NUGET_DIRECTORY }} -p:ContinuousIntegrationBuild=true -p:publicrelease=true - dotnet pack src/bunit.web/ -c Release --output ${{ env.NUGET_DIRECTORY }} -p:ContinuousIntegrationBuild=true -p:publicrelease=true dotnet pack src/bunit.template/ -c Release --output ${{ env.NUGET_DIRECTORY }} -p:ContinuousIntegrationBuild=true -p:publicrelease=true dotnet pack src/bunit.generators/ -c release --output ${{ env.NUGET_DIRECTORY }} -p:ContinuousIntegrationBuild=true -p:publicrelease=true dotnet pack src/bunit.web.query/ -c release --output ${{ env.NUGET_DIRECTORY }} -p:ContinuousIntegrationBuild=true -p:publicrelease=true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2738b7e35..4aa8f9894 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -95,8 +95,6 @@ jobs: - name: 🛠️ Packing library in release mode run: | dotnet pack src/bunit/ -c Release --property:PackageOutputPath=${GITHUB_WORKSPACE}/packages -p:ContinuousIntegrationBuild=true -p:publicrelease=true - dotnet pack src/bunit.core/ -c Release --property:PackageOutputPath=${GITHUB_WORKSPACE}/packages -p:ContinuousIntegrationBuild=true -p:publicrelease=true - dotnet pack src/bunit.web/ -c Release --property:PackageOutputPath=${GITHUB_WORKSPACE}/packages -p:ContinuousIntegrationBuild=true -p:publicrelease=true dotnet pack src/bunit.template/ -c Release --property:PackageOutputPath=${GITHUB_WORKSPACE}/packages -p:ContinuousIntegrationBuild=true -p:publicrelease=true - name: 🛠️ Upload library to NuGet.org repository From 7678768c5a88758799b1cccd1c4a3c6b11a36959 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 16:48:33 +0100 Subject: [PATCH 024/100] refactor: Remove old versions in ci.yml --- .github/workflows/ci.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 522e8009c..2df772056 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,7 @@ on: paths: - 'src/**' - 'tests/**' + - 'docs/**' pull_request: types: @@ -18,7 +19,7 @@ on: workflow_dispatch: concurrency: - group: verification-${{ github.workflow }}-${{ github.ref == 'refs/heads/main' && github.run_id || github.event.pull_request.number || github.ref }} + group: ci-${{ github.workflow }}-${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/v2') && github.run_id || github.event.pull_request.number || github.ref }} cancel-in-progress: true env: @@ -44,10 +45,6 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 3.1.x - 5.0.x - 6.0.x - 7.0.x 8.0.x 9.0.x From 9b0545dcb2150448e65729a23518f7e90f7981e8 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 16:57:52 +0100 Subject: [PATCH 025/100] fix: Template use latest dotnet version --- .../template/.template.config/template.json | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/bunit.template/template/.template.config/template.json b/src/bunit.template/template/.template.config/template.json index f926c5c55..3fe504aac 100644 --- a/src/bunit.template/template/.template.config/template.json +++ b/src/bunit.template/template/.template.config/template.json @@ -82,23 +82,18 @@ "description": "The target framework sdk for the project.", "displayName": "Target framework sdk", "datatype": "choice", - "defaultValue": "net7.0", + "defaultValue": "net8.0", "replaces": "targetSdk", "choices": [ - { - "choice": "net6.0", - "description": ".net 6.0", - "displayName": ".net 6.0" - }, - { - "choice": "net7.0", - "description": ".net 7.0", - "displayName": ".net 7.0" - }, { "choice": "net8.0", "description": ".net 8.0", "displayName": ".net 8.0" + }, + { + "choice": "net9.0", + "description": ".net 9.0", + "displayName": ".net 9.0" } ] } From 451072f8271f265f5b476c8f7142b8dc3df808f9 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 17:48:14 +0100 Subject: [PATCH 026/100] fix: Docs and references --- docs/samples/tests/razor/TemplateParams1Test.razor | 14 ++++++++++++++ docs/samples/tests/razor/TemplateParams2Test.razor | 14 ++++++++++++++ docs/site/docfx.json | 3 +-- docs/site/docs/interaction/awaiting-async-state.md | 4 ++-- docs/site/docs/interaction/dispose-components.md | 2 +- docs/site/docs/interaction/trigger-renders.md | 12 ++++++------ .../passing-parameters-to-components.md | 2 +- docs/site/docs/test-doubles/auth.md | 4 ++-- docs/site/docs/verification/async-assertion.md | 4 ++-- .../docs/verification/verify-component-state.md | 2 +- 10 files changed, 44 insertions(+), 17 deletions(-) create mode 100644 docs/samples/tests/razor/TemplateParams1Test.razor create mode 100644 docs/samples/tests/razor/TemplateParams2Test.razor diff --git a/docs/samples/tests/razor/TemplateParams1Test.razor b/docs/samples/tests/razor/TemplateParams1Test.razor new file mode 100644 index 000000000..857f34e99 --- /dev/null +++ b/docs/samples/tests/razor/TemplateParams1Test.razor @@ -0,0 +1,14 @@ +@inherits BunitContext + +@code +{ + [Fact] + public void Test() + { + var cut = Render(@ + + ); + } +} \ No newline at end of file diff --git a/docs/samples/tests/razor/TemplateParams2Test.razor b/docs/samples/tests/razor/TemplateParams2Test.razor new file mode 100644 index 000000000..3b4754476 --- /dev/null +++ b/docs/samples/tests/razor/TemplateParams2Test.razor @@ -0,0 +1,14 @@ +@inherits BunitContext + +@code +{ + [Fact] + public void Test() + { + var cut = Render(@ + + ); + } +} \ No newline at end of file diff --git a/docs/site/docfx.json b/docs/site/docfx.json index 1295441d0..bb86f0d14 100644 --- a/docs/site/docfx.json +++ b/docs/site/docfx.json @@ -5,8 +5,7 @@ "src": [ { "files": [ - "bunit.core/**/bin/Release/**.dll", - "bunit.web/**/bin/Release/**.dll" + "bunit/**/bin/Release/**.dll" ], "src": "../../src" } diff --git a/docs/site/docs/interaction/awaiting-async-state.md b/docs/site/docs/interaction/awaiting-async-state.md index 165a59e16..f0920dc1c 100644 --- a/docs/site/docs/interaction/awaiting-async-state.md +++ b/docs/site/docs/interaction/awaiting-async-state.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{TimeSpan})) method covered on the page. Let's start by taking a look at the `WaitForState` method in more detail. ## Waiting for state using `WaitForState` -The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) +The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) > [!NOTE] > The `WaitForState()` method will try the predicate passed to it when the `WaitForState()` method is called, and every time the component under test renders. diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index 55f16fcb0..1d81065c9 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -13,7 +13,7 @@ The following example of this: [!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] > [!WARNING] -> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. +> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Checking for exceptions `Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponents) will throw the exception to the user code: diff --git a/docs/site/docs/interaction/trigger-renders.md b/docs/site/docs/interaction/trigger-renders.md index 496f92d21..52eb4acc8 100644 --- a/docs/site/docs/interaction/trigger-renders.md +++ b/docs/site/docs/interaction/trigger-renders.md @@ -17,25 +17,25 @@ Let's look at how to use each of these methods to cause a re-render. ## Render -The [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0})) method tells the renderer to re-render the component, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods). To use it, do the following: +The [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0})) method tells the renderer to re-render the component, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods). To use it, do the following: [!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=15&end=21&highlight=5)] -The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0})). +The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0})). > [!TIP] > The number of renders a component has been through can be inspected and verified using the property. ## Render -The [`Render(...)`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods tells the renderer to re-render the component with new parameters, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods), passing the new parameters — _but only the new parameters_ — to the `SetParametersAsync()` method. To use it, do the following: +The [`Render(...)`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods tells the renderer to re-render the component with new parameters, i.e. go through its life-cycle methods (except for `OnInitialized()` and `OnInitializedAsync()` methods), passing the new parameters — _but only the new parameters_ — to the `SetParametersAsync()` method. To use it, do the following: [!code-csharp[](../../../samples/tests/xunit/ReRenderTest.cs?start=28&end=38&highlight=7-9)] -The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})), which is also available as a version that takes the zero or more component parameters, e.g. created through the component parameter factory helper methods, if you prefer that method of passing parameters. +The highlighted line shows the call to [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})), which is also available as a version that takes the zero or more component parameters, e.g. created through the component parameter factory helper methods, if you prefer that method of passing parameters. > [!NOTE] -> Passing parameters to components through the [`Render(...)`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods is identical to doing it with the `Render(...)` methods, described in detail on the page. +> Passing parameters to components through the [`Render(...)`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods is identical to doing it with the `Render(...)` methods, described in detail on the page. ## InvokeAsync @@ -56,7 +56,7 @@ To invoke the `Calculate()` method on the component instance, do the following: The highlighted line shows the call to `InvokeAsync()`, which is passed an `Action` delegate that calls the `Calculate` method. > [!TIP] -> The instance of a component under test is available through the property. +> The instance of a component under test is available through the property. ### Advanced use cases diff --git a/docs/site/docs/providing-input/passing-parameters-to-components.md b/docs/site/docs/providing-input/passing-parameters-to-components.md index 410b4c1e8..08f8f522c 100644 --- a/docs/site/docs/providing-input/passing-parameters-to-components.md +++ b/docs/site/docs/providing-input/passing-parameters-to-components.md @@ -221,7 +221,7 @@ Some times you need to pass multiple different types of content to a `RenderFrag [!code-csharp[RenderFragmentParamsTest.cs](../../../samples/tests/xunit/RenderFragmentParams4Test.cs#L11-L27)] -Passing a mix of markup and components to a `RenderFragment` parameter is simply done by calling the 's `Add()` methods or using the `ChildContent()` factory methods in , as seen here. +Passing a mix of markup and components to a `RenderFragment` parameter is simply done by calling the 's `Add()` methods or using the `AddChildContent` factory methods. # [Razor test code](#tab/razor) diff --git a/docs/site/docs/test-doubles/auth.md b/docs/site/docs/test-doubles/auth.md index d366355bd..736cdad29 100644 --- a/docs/site/docs/test-doubles/auth.md +++ b/docs/site/docs/test-doubles/auth.md @@ -15,10 +15,10 @@ The test implementation of Blazor's authentication and authorization can be put - **Authenticated** and **authorized** - **Authenticated** and **authorized** with one or more **roles**, **claims**, and/or **policies** -bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.BunitContext.AddAuthorization(Bunit.BunitContext)) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. +bUnit's authentication and authorization implementation is easily available by calling [`AddAuthorization()`](xref:Bunit.BunitContext.AddAuthorization()) on a test context. This adds the necessary services to the `Services` collection and the `CascadingAuthenticationState` component to the [root render tree](xref:root-render-tree). The method returns an instance of the type that allows you to control the authentication and authorization state for a test. > [!NOTE] -> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.BunitContext.AddAuthorization(Bunit.BunitContext)) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `AddAuthorization()`. +> If your test class inherits directly from bUnit's then you need to call the [`AddAuthorization()`](xref:Bunit.BunitContext.AddAuthorization()) method on `this`, since `AddAuthorization()` is an extension method, otherwise it wont be available. E.g.: `AddAuthorization()`. The following sections show how to set each of these states in a test. diff --git a/docs/site/docs/verification/async-assertion.md b/docs/site/docs/verification/async-assertion.md index 459870ff0..4683c5711 100644 --- a/docs/site/docs/verification/async-assertion.md +++ b/docs/site/docs/verification/async-assertion.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass, and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,Func{System.Boolean},System.Nullable{TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) method covered on the page. Let's start by taking a look at the ` WaitForAssertion` method in more detail. ## Waiting for assertion to pass using `WaitForAssertion` -The [`WaitForAssertion(Action, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,Action,System.Nullable{TimeSpan})) method can be used to block and wait in a test method until the provided assert action does not throw an exception, or until the timeout is reached (the default timeout is one second). +The [`WaitForAssertion(Action, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{TimeSpan})) method can be used to block and wait in a test method until the provided assert action does not throw an exception, or until the timeout is reached (the default timeout is one second). > [!NOTE] > The `WaitForAssertion()` method will try the assert action passed to it when the `WaitForAssertion()` method is called and every time the component under test renders. diff --git a/docs/site/docs/verification/verify-component-state.md b/docs/site/docs/verification/verify-component-state.md index 0030137ba..79b1bf6b9 100644 --- a/docs/site/docs/verification/verify-component-state.md +++ b/docs/site/docs/verification/verify-component-state.md @@ -27,7 +27,7 @@ Alert alert = cut.Instance; > [!WARNING] > While it is possible to set `[Parameter]` and `[CascadingParameter]` properties directly through the property on the type, doing so does not implicitly trigger a render and the component life-cycle methods are not called. > -> The correct approach is to set parameters through the [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods. See the page for more on this. +> The correct approach is to set parameters through the [`Render()`](xref:Bunit.RenderedComponentRenderExtensions.Render``1(Bunit.RenderedComponent{``0},System.Action{Bunit.ComponentParameterCollectionBuilder{``0}})) methods. See the page for more on this. ## Finding Components in the Render Tree From d6cb456ee65f3c58936f31235b83efbccf8ab45e Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 8 Mar 2024 23:40:26 +0100 Subject: [PATCH 027/100] fix: Documentation links --- docs/site/docs/interaction/awaiting-async-state.md | 4 ++-- docs/site/docs/interaction/dispose-components.md | 2 +- docs/site/docs/interaction/trigger-event-handlers.md | 2 +- docs/site/docs/interaction/trigger-renders.md | 4 ++-- docs/site/docs/test-doubles/auth.md | 4 ++-- docs/site/docs/verification/async-assertion.md | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/site/docs/interaction/awaiting-async-state.md b/docs/site/docs/interaction/awaiting-async-state.md index f0920dc1c..e26d62183 100644 --- a/docs/site/docs/interaction/awaiting-async-state.md +++ b/docs/site/docs/interaction/awaiting-async-state.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{System.TimeSpan})) method covered on the page. Let's start by taking a look at the `WaitForState` method in more detail. ## Waiting for state using `WaitForState` -The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) +The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) > [!NOTE] > The `WaitForState()` method will try the predicate passed to it when the `WaitForState()` method is called, and every time the component under test renders. diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index 1d81065c9..acbdd314f 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -13,7 +13,7 @@ The following example of this: [!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] > [!WARNING] -> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{TimeSpan})) will not work as a disposed component will not trigger a new render cycle. +> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{System.TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Checking for exceptions `Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponents) will throw the exception to the user code: diff --git a/docs/site/docs/interaction/trigger-event-handlers.md b/docs/site/docs/interaction/trigger-event-handlers.md index e10478621..f030ed4f5 100644 --- a/docs/site/docs/interaction/trigger-event-handlers.md +++ b/docs/site/docs/interaction/trigger-event-handlers.md @@ -51,7 +51,7 @@ This is what happens in the test: 1. In the arrange step of the test, the `` component is rendered and the ` - public TestServiceProvider Services { get; } + public BunitServiceProvider Services { get; } /// /// Gets the that all components rendered with the @@ -58,7 +58,7 @@ public partial class BunitContext : IDisposable, IAsyncDisposable /// public BunitContext() { - Services = new TestServiceProvider(); + Services = new BunitServiceProvider(); Services.AddSingleton(_ => ComponentFactories); Services.AddDefaultBunitContextServices(this, JSInterop); } diff --git a/src/bunit/TestServiceProvider.cs b/src/bunit/BunitServiceProvider.cs similarity index 93% rename from src/bunit/TestServiceProvider.cs rename to src/bunit/BunitServiceProvider.cs index 4afcb176d..0748b95ec 100644 --- a/src/bunit/TestServiceProvider.cs +++ b/src/bunit/BunitServiceProvider.cs @@ -6,7 +6,7 @@ namespace Bunit; /// Represents a and /// as a single type used for test purposes. ///
    -public sealed class TestServiceProvider : IKeyedServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable +public sealed class BunitServiceProvider : IKeyedServiceProvider, IServiceCollection, IDisposable, IAsyncDisposable { private static readonly ServiceProviderOptions DefaultServiceProviderOptions = new() { ValidateScopes = true }; private readonly IServiceCollection serviceCollection; @@ -18,7 +18,7 @@ public sealed class TestServiceProvider : IKeyedServiceProvider, IServiceCollect private Func serviceProviderFactory; /// - /// Gets a value indicating whether this has been initialized, and + /// Gets a value indicating whether this has been initialized, and /// no longer will accept calls to the AddService's methods. /// public bool IsProviderInitialized => serviceProvider is not null; @@ -50,15 +50,15 @@ public ServiceProviderOptions Options } /// - /// Initializes a new instance of the class + /// Initializes a new instance of the class /// and sets its service collection to the provided , if any. /// - public TestServiceProvider(IServiceCollection? initialServiceCollection = null) + public BunitServiceProvider(IServiceCollection? initialServiceCollection = null) : this(initialServiceCollection ?? new ServiceCollection(), initializeProvider: false) { } - private TestServiceProvider(IServiceCollection initialServiceCollection, bool initializeProvider) + private BunitServiceProvider(IServiceCollection initialServiceCollection, bool initializeProvider) { serviceCollection = initialServiceCollection; serviceProviderFactory = () => serviceCollection.BuildServiceProvider(Options); @@ -110,7 +110,7 @@ private void InitializeProvider() { CheckInitializedAndThrow(); - serviceCollection.AddSingleton(this); + serviceCollection.AddSingleton(this); rootServiceProvider = serviceProviderFactory.Invoke(); serviceScope = rootServiceProvider.CreateScope(); serviceProvider = serviceScope.ServiceProvider; diff --git a/src/bunit/Extensions/TestServiceProviderExtensions.cs b/src/bunit/Extensions/BunitServiceProviderExtensions.cs similarity index 97% rename from src/bunit/Extensions/TestServiceProviderExtensions.cs rename to src/bunit/Extensions/BunitServiceProviderExtensions.cs index baa029fa7..4b89b03bb 100644 --- a/src/bunit/Extensions/TestServiceProviderExtensions.cs +++ b/src/bunit/Extensions/BunitServiceProviderExtensions.cs @@ -12,7 +12,7 @@ namespace Bunit.Extensions; /// /// Helper methods for correctly registering test dependencies. /// -public static class TestServiceProviderExtensions +public static class BunitServiceProviderExtensions { /// /// Registers the default services required by the web . diff --git a/src/bunit/Rendering/BunitRenderer.cs b/src/bunit/Rendering/BunitRenderer.cs index d91d67d1b..ef9cdfb16 100644 --- a/src/bunit/Rendering/BunitRenderer.cs +++ b/src/bunit/Rendering/BunitRenderer.cs @@ -10,7 +10,7 @@ namespace Bunit.Rendering; /// public sealed class BunitRenderer : Renderer { - private readonly TestServiceProvider services; + private readonly BunitServiceProvider services; [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")] private static extern ref bool GetIsBatchInProgressField(Renderer renderer); @@ -57,7 +57,7 @@ private bool IsBatchInProgress /// /// Initializes a new instance of the class. /// - public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory) + public BunitRenderer(BunitServiceProvider services, ILoggerFactory loggerFactory) : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), null)) { this.services = services; @@ -68,7 +68,7 @@ public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory) /// /// Initializes a new instance of the class. /// - public BunitRenderer(TestServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) + public BunitRenderer(BunitServiceProvider services, ILoggerFactory loggerFactory, IComponentActivator componentActivator) : base(services, loggerFactory, new BunitComponentActivator(services.GetRequiredService(), componentActivator)) { this.services = services; diff --git a/src/bunit/Rendering/RenderedFragment.cs b/src/bunit/Rendering/RenderedFragment.cs index dc7efbeb0..3f817d2a6 100644 --- a/src/bunit/Rendering/RenderedFragment.cs +++ b/src/bunit/Rendering/RenderedFragment.cs @@ -10,7 +10,7 @@ namespace Bunit; [DebuggerDisplay("Rendered:{RenderCount}")] public class RenderedFragment : IDisposable { - [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by TestServiceProvider, disposed by it.")] + [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Owned by BunitServiceProvider, disposed by it.")] private readonly BunitHtmlParser htmlParser; private string markup = string.Empty; private INodeList? latestRenderNodes; diff --git a/src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs index 0667cf429..25942ac0a 100644 --- a/src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationContext.cs @@ -53,7 +53,7 @@ public class BunitAuthorizationContext /// /// Creates a new instance of . /// - internal BunitAuthorizationContext(TestServiceProvider services) + internal BunitAuthorizationContext(BunitServiceProvider services) { services.AddSingleton(authService); services.AddSingleton(policyProvider); diff --git a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs index 738b5abb8..cb7c5ad83 100644 --- a/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs +++ b/src/bunit/TestDoubles/Authorization/BunitAuthorizationExtensions.cs @@ -7,7 +7,7 @@ namespace Bunit; public partial class BunitContext { /// - /// Adds the appropriate Blazor authentication and authorization services to the to enable + /// Adds the appropriate Blazor authentication and authorization services to the to enable /// an authenticated user, as well as adding the component to the /// test contexts render tree. /// diff --git a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs index 73ea41590..e3c9bcaad 100644 --- a/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs +++ b/src/bunit/TestDoubles/PersistentComponentState/BunitPersistentComponentState.cs @@ -38,7 +38,7 @@ internal BunitPersistentComponentState(IServiceProvider services) /// /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the - /// from the , which means no other services can be registered after this point. + /// from the , which means no other services can be registered after this point. /// public void TriggerOnPersisting() { @@ -52,7 +52,7 @@ public void TriggerOnPersisting() /// /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the - /// from the , which means no other services can be registered after this point. + /// from the , which means no other services can be registered after this point. /// /// The type. /// The key to use to persist the state. @@ -72,7 +72,7 @@ public void Persist(string key, TValue instance) /// /// Only call this method after all services has been registered with the . /// Calling this method will lookup dependencies of the - /// from the , which means no other services can be registered after this point. + /// from the , which means no other services can be registered after this point. /// /// The key used to persist the instance. /// The persisted instance. diff --git a/tests/bunit.tests/TestServiceProviderTest.cs b/tests/bunit.tests/BunitServiceProviderTests.cs similarity index 93% rename from tests/bunit.tests/TestServiceProviderTest.cs rename to tests/bunit.tests/BunitServiceProviderTests.cs index 75facc538..91d88a8dd 100644 --- a/tests/bunit.tests/TestServiceProviderTest.cs +++ b/tests/bunit.tests/BunitServiceProviderTests.cs @@ -2,12 +2,12 @@ namespace Bunit; -public partial class TestServiceProviderTest +public partial class BunitServiceProviderTests { [Fact(DisplayName = "Provider initialized without a service collection has zero services by default")] public void Test001() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.Count.ShouldBe(0); } @@ -17,7 +17,7 @@ public void Test002() { var services = new ServiceCollection(); services.AddSingleton(new DummyService()); - using var sut = new TestServiceProvider(services); + using var sut = new BunitServiceProvider(services); sut.Count.ShouldBe(1); sut[0].ServiceType.ShouldBe(typeof(DummyService)); @@ -26,7 +26,7 @@ public void Test002() [Fact(DisplayName = "Services can be registered in the provider like a normal service collection")] public void Test010() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.Add(new ServiceDescriptor(typeof(DummyService), new DummyService())); sut.Insert(0, new ServiceDescriptor(typeof(AnotherDummyService), new AnotherDummyService())); @@ -40,7 +40,7 @@ public void Test010() [Fact(DisplayName = "Services can be removed in the provider like a normal service collection")] public void Test011() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); var descriptor = new ServiceDescriptor(typeof(DummyService), new DummyService()); var anotherDescriptor = new ServiceDescriptor(typeof(AnotherDummyService), new AnotherDummyService()); var oneMoreDescriptor = new ServiceDescriptor(typeof(OneMoreDummyService), new OneMoreDummyService()); @@ -62,7 +62,7 @@ public void Test011() [Fact(DisplayName = "Misc collection methods works as expected")] public void Test012() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); var descriptor = new ServiceDescriptor(typeof(DummyService), new DummyService()); var copyToTarget = new ServiceDescriptor[1]; sut.Add(descriptor); @@ -81,7 +81,7 @@ public void Test013() { var descriptor = new ServiceDescriptor(typeof(AnotherDummyService), new AnotherDummyService()); - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddSingleton(new DummyService()); sut.GetService(); @@ -103,7 +103,7 @@ public void Test013() [Fact(DisplayName = "Registered services can be retrieved from the provider")] public void Test020() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); var expected = new DummyService(); sut.AddSingleton(expected); @@ -115,7 +115,7 @@ public void Test020() [Fact(DisplayName = "No registered service returns null")] public void Test021() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); var result = sut.GetService(typeof(DummyService)); @@ -125,7 +125,7 @@ public void Test021() [Fact(DisplayName = "Registered fallback service provider returns value")] public void Test022() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddFallbackServiceProvider(new FallbackServiceProvider()); var result = sut.GetService(typeof(object)); @@ -137,7 +137,7 @@ public void Test022() [Fact(DisplayName = "Register fallback service with null value")] public void Test023() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); Assert.Throws(() => sut.AddFallbackServiceProvider(null!)); } @@ -146,7 +146,7 @@ public void Test024() { const string exceptionStringResult = "exceptionStringResult"; - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddSingleton(exceptionStringResult); sut.AddFallbackServiceProvider(new FallbackServiceProvider()); @@ -160,7 +160,7 @@ public void Test024() [Fact(DisplayName = "Latest fallback provider is used")] public void Test025() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddFallbackServiceProvider(new FallbackServiceProvider()); sut.AddFallbackServiceProvider(new AnotherFallbackServiceProvider()); @@ -186,7 +186,7 @@ public void Test030() [Fact(DisplayName = "Can correctly resolve and dispose of scoped disposable service")] public void Test031() { - var sut = new TestServiceProvider(); + var sut = new BunitServiceProvider(); sut.AddScoped(); var disposable = sut.GetService(); @@ -198,7 +198,7 @@ public void Test031() [Fact(DisplayName = "Can correctly resolve and dispose of transient disposable service")] public void Test032() { - var sut = new TestServiceProvider(); + var sut = new BunitServiceProvider(); sut.AddTransient(); var disposable = sut.GetService(); @@ -210,7 +210,7 @@ public void Test032() [Fact(DisplayName = "Can correctly resolve and dispose of singleton disposable service")] public void Test033() { - var sut = new TestServiceProvider(); + var sut = new BunitServiceProvider(); sut.AddSingleton(); var disposable = sut.GetService(); @@ -222,7 +222,7 @@ public void Test033() [Fact(DisplayName = "Validates that all dependencies can be created when the first service is requested, if ServiceProviderOptions.ValidateOnBuild is true")] public void Test035() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.Options = new ServiceProviderOptions { ValidateOnBuild = true, @@ -238,7 +238,7 @@ public void Test035() [Fact(DisplayName = "Does not validate all dependencies can be created when the first service is requested, if ServiceProviderOptions.ValidateOnBuild is false")] public void Test036() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.Options = new ServiceProviderOptions { ValidateOnBuild = false, @@ -255,7 +255,7 @@ public void Test036() [Fact(DisplayName = "Does not validate all dependencies can be created when the first service is requested, if no ServiceProviderOptions is provided (backwards compatibility)")] public void Test037() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddSingleton(); sut.AddSingleton(); @@ -267,7 +267,7 @@ public void Test037() [Fact(DisplayName = "Test custom service provider factory")] public void Test038() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddSingleton(); var dummyServiceProviderFactory = new DummyServiceProviderFactory(); sut.UseServiceProviderFactory(dummyServiceProviderFactory); @@ -284,7 +284,7 @@ public void Test038() [Fact(DisplayName = "Test custom service provider factory as delegate")] public void Test039() { - using var sut = new TestServiceProvider(); + using var sut = new BunitServiceProvider(); sut.AddSingleton(); DummyServiceProvider dummyServiceProvider = null; sut.UseServiceProviderFactory(x => dummyServiceProvider = new DummyServiceProvider(x)); From a68ff322268899db901c2cf95b72b1ba63fa943d Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Wed, 13 Mar 2024 07:17:41 +0100 Subject: [PATCH 031/100] feat: Add flag to actively wait for async disposal (#1415) --- MIGRATION.md | 3 ++ .../components/AsyncDisposableComponent.razor | 10 ++++ .../tests/xunit/DisposeComponentsTest.cs | 25 +++++++--- .../docs/interaction/dispose-components.md | 21 +++++++-- src/bunit/BunitContext.cs | 5 +- src/bunit/Rendering/BunitRenderer.cs | 40 +++++++++++++--- .../TaskAssertionExtensions.cs | 9 ---- tests/bunit.tests/BunitContextTest.cs | 46 ++++++++----------- 8 files changed, 102 insertions(+), 57 deletions(-) create mode 100644 docs/samples/components/AsyncDisposableComponent.razor delete mode 100644 tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs diff --git a/MIGRATION.md b/MIGRATION.md index 05b451446..275a9c313 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -79,3 +79,6 @@ Or use the `BunitContext` directly and manage the lifecycle yourself. ## `TestServiceProvider` renamed to `BunitTestServiceProvider` The `TestServiceProvider` class has been renamed to `BunitTestServiceProvider`. If you used `TestServiceProvider`, you should replace it with `BunitTestServiceProvider`. + +## `DisposeComponents` is now asynchronous and called `DisposeComponentsAsync` +`DisposeComponentsAsync` allows to await `DisposeAsync` of components under test. If you used `DisposeComponents`, you should replace it with `DisposeComponentsAsync`. diff --git a/docs/samples/components/AsyncDisposableComponent.razor b/docs/samples/components/AsyncDisposableComponent.razor new file mode 100644 index 000000000..0d3851b3e --- /dev/null +++ b/docs/samples/components/AsyncDisposableComponent.razor @@ -0,0 +1,10 @@ +@using Microsoft.JSInterop +@implements IAsyncDisposable +@inject IJSRuntime JSRuntime +@code { + + public async ValueTask DisposeAsync() + { + await JSRuntime.InvokeVoidAsync("dispose"); + } +} diff --git a/docs/samples/tests/xunit/DisposeComponentsTest.cs b/docs/samples/tests/xunit/DisposeComponentsTest.cs index 1f6e30b84..bf651ff94 100644 --- a/docs/samples/tests/xunit/DisposeComponentsTest.cs +++ b/docs/samples/tests/xunit/DisposeComponentsTest.cs @@ -8,14 +8,14 @@ namespace Bunit.Docs.Samples; public class DisposeComponentsTest : BunitContext { [Fact] - public void DisposeElements() + public async Task DisposeElements() { var calledTimes = 0; var cut = Render(parameters => parameters .Add(p => p.LocationChangedCallback, url => calledTimes++) ); - DisposeComponents(); + await DisposeComponentsAsync(); Services.GetRequiredService().NavigateTo("newurl"); @@ -23,22 +23,33 @@ public void DisposeElements() } [Fact] - public void ShouldCatchExceptionInDispose() + public async Task ShouldCatchExceptionInDispose() { Render(); - var act = DisposeComponents; + Func act = () => DisposeComponentsAsync(); - Assert.Throws(act); + await Assert.ThrowsAsync(act); } [Fact] - public void ShouldCatchExceptionInDisposeAsync() + public async Task ShouldCatchExceptionInDisposeAsync() { Render(); - DisposeComponents(); + await DisposeComponentsAsync(); var exception = Renderer.UnhandledException.Result; Assert.IsType(exception); } + + [Fact] + public async Task ShouldDisposeJSObject() + { + JSInterop.SetupVoid("dispose").SetVoidResult(); + Render(); + + await DisposeComponentsAsync(); + + JSInterop.VerifyInvoke("dispose"); + } } \ No newline at end of file diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index acbdd314f..916ed5a61 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -4,22 +4,33 @@ title: Disposing components and their children --- # Disposing components -To dispose all components rendered with a `BunitContext`, use the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponents) method. Calling this method will dispose all rendered components, calling any `IDisposable.Dispose` or/and `IAsyncDisposable.DisposeAsync` methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components. +To dispose all components rendered with a `BunitContext`, use the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponentsAsync) method. Calling this method will dispose all rendered components, calling any `IDisposable.Dispose` or/and `IAsyncDisposable.DisposeAsync` methods they might have, and remove the components from the render tree, starting with the root components and then walking down the render tree to all the child components. Disposing rendered components enables testing of logic in `Dispose` methods, e.g., event handlers, that should be detached to avoid memory leaks. The following example of this: -[!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] +[!code-csharp[DisposeComponentsTest.cs](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] > [!WARNING] > For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{System.TimeSpan})) will not work as a disposed component will not trigger a new render cycle. +## Disposing components asynchronously +If a component implements `IAsyncDisposable`, `DisposeComponentsAsync` can be awaited to wait for all asynchronous `DisposeAsync` methods. Sometimes interacting with JavaScript in Blazor WebAssembly requires disposing or resetting state in `DisposeAsync`. + +[!code-csharp[DisposeComponentsTest.cs](../../../samples/tests/xunit/DisposeComponentsTest.cs#L48-L53)] + +To omit this behavior, discard the returned task + +```csharp +_ = DisposeComponentsAsync(); +``` + ## Checking for exceptions -`Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponents) will throw the exception to the user code: +`Dispose` as well as `DisposeAsync` can throw exceptions which can be asserted as well. If a component under test throws an exception in `Dispose` the [`DisposeComponents`](xref:Bunit.BunitContext.DisposeComponentsAsync) will throw the exception to the user code: -[!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L28-L32)] +[!code-csharp[DisposeComponentsTest.cs](../../../samples/tests/xunit/DisposeComponentsTest.cs#L28-L32)] `DisposeAsync` behaves a bit different. The following example will demonstrate how to assert an exception in `DisposeAsync`: -[!code-csharp[](../../../samples/tests/xunit/DisposeComponentsTest.cs#L39-L43)] \ No newline at end of file +[!code-csharp[DisposeComponentsTest.cs](../../../samples/tests/xunit/DisposeComponentsTest.cs#L38-L42)] \ No newline at end of file diff --git a/src/bunit/BunitContext.cs b/src/bunit/BunitContext.cs index b7241cbe6..77212ea2e 100644 --- a/src/bunit/BunitContext.cs +++ b/src/bunit/BunitContext.cs @@ -130,10 +130,7 @@ protected virtual void Dispose(bool disposing) /// /// Disposes all components rendered via this . /// - public void DisposeComponents() - { - Renderer.DisposeComponents(); - } + public Task DisposeComponentsAsync() => Renderer.DisposeComponents(); /// /// Instantiates and performs a first render of a component of type . diff --git a/src/bunit/Rendering/BunitRenderer.cs b/src/bunit/Rendering/BunitRenderer.cs index ef9cdfb16..34cf8ee8e 100644 --- a/src/bunit/Rendering/BunitRenderer.cs +++ b/src/bunit/Rendering/BunitRenderer.cs @@ -11,6 +11,7 @@ namespace Bunit.Rendering; public sealed class BunitRenderer : Renderer { private readonly BunitServiceProvider services; + private readonly List disposalTasks = []; [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_isBatchInProgress")] private static extern ref bool GetIsBatchInProgressField(Renderer renderer); @@ -178,17 +179,15 @@ public IReadOnlyList> FindComponents(R /// /// Disposes all components rendered by the . /// - public void DisposeComponents() + public Task DisposeComponents() { ObjectDisposedException.ThrowIf(disposed, this); + Task? returnTask; + lock (renderTreeUpdateLock) { - // The dispatcher will always return a completed task, - // when dealing with an IAsyncDisposable. - // Therefore checking for a completed task and awaiting it - // will only work on IDisposable - Dispatcher.InvokeAsync(() => + returnTask = Dispatcher.InvokeAsync(async () => { ResetUnhandledException(); @@ -196,11 +195,16 @@ public void DisposeComponents() { root.Detach(); } + + await Task.WhenAll(disposalTasks).ConfigureAwait(false); + disposalTasks.Clear(); }); rootComponents.Clear(); AssertNoUnhandledExceptions(); } + + return returnTask; } /// @@ -212,6 +216,29 @@ protected override IComponent ResolveComponentForRenderMode(Type componentType, return componentActivator.CreateInstance(componentType); } + /// + protected override void AddPendingTask(ComponentState? componentState, Task task) + { + if (componentState is null) + { + ArgumentNullException.ThrowIfNull(task); + AddDisposalTaskToQueue(); + } + + base.AddPendingTask(componentState, task); + + void AddDisposalTaskToQueue() + { + var t = task; + t = task.ContinueWith(_ => + { + disposalTasks.Remove(t); + }, TaskScheduler.Current); + + disposalTasks.Add(t); + } + } + internal Task SetDirectParametersAsync(RenderedFragment renderedComponent, ParameterView parameters) { ObjectDisposedException.ThrowIf(disposed, this); @@ -412,6 +439,7 @@ protected override void Dispose(bool disposing) } renderedComponents.Clear(); + disposalTasks.Clear(); unhandledExceptionTsc.TrySetCanceled(); } diff --git a/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs b/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs deleted file mode 100644 index 48adfd2c5..000000000 --- a/tests/bunit.testassets/AssertExtensions/TaskAssertionExtensions.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Bunit; - -public static class TaskAssertionExtensions -{ - public static async Task ShouldCompleteWithin(this Task task, TimeSpan timeout) - { - await task.WaitAsync(timeout); - } -} diff --git a/tests/bunit.tests/BunitContextTest.cs b/tests/bunit.tests/BunitContextTest.cs index be5e6e98c..a651cc44b 100644 --- a/tests/bunit.tests/BunitContextTest.cs +++ b/tests/bunit.tests/BunitContextTest.cs @@ -6,12 +6,12 @@ namespace Bunit; public class BunitContextTest : BunitContext { [Fact(DisplayName = "DisposeComponents disposes rendered components in parent to child order")] - public void Test101() + public async Task Test101() { var callStack = new List(); Render(ps => ps.Add(p => p.CallStack, callStack)); - DisposeComponents(); + await DisposeComponentsAsync(); callStack.Count.ShouldBe(2); callStack[0].ShouldBe("ParentDispose"); @@ -19,33 +19,33 @@ public void Test101() } [Fact(DisplayName = "DisposeComponents disposes multiple rendered components")] - public void Test102() + public async Task Test102() { var callStack = new List(); Render(ps => ps.Add(p => p.CallStack, callStack)); Render(ps => ps.Add(p => p.CallStack, callStack)); - DisposeComponents(); + await DisposeComponentsAsync(); callStack.Count.ShouldBe(2); } [Fact(DisplayName = "DisposeComponents rethrows exceptions from Dispose methods in components")] - public void Test103() + public async Task Test103() { Render(); - var action = () => DisposeComponents(); + Func action = () => DisposeComponentsAsync(); - action.ShouldThrow(); + await action.ShouldThrowAsync(); } [Fact(DisplayName = "DisposeComponents disposes components nested in render fragments")] - public void Test104() + public async Task Test104() { var callStack = new List(); Render(DisposeFragments.ChildDisposeAsFragment(callStack)); - DisposeComponents(); + await DisposeComponentsAsync(); callStack.Count.ShouldBe(1); } @@ -171,16 +171,12 @@ public void Test0003() [Fact(DisplayName = "DisposeComponents captures exceptions from DisposeAsync in Renderer.UnhandledException")] public async Task Test201() { - var tcs = new TaskCompletionSource(); - var expected = new NotSupportedException(); - Render( - ps => ps.Add(p => p.DisposedTask, tcs.Task)); + Render(); - DisposeComponents(); + await DisposeComponentsAsync(); - tcs.SetException(expected); var actual = await Renderer.UnhandledException; - actual.ShouldBeSameAs(expected); + actual.ShouldBeAssignableTo(); } [Fact(DisplayName = "DisposeComponents calls DisposeAsync on rendered components")] @@ -189,19 +185,19 @@ public async Task Test202() var cut = Render(); var wasDisposedTask = cut.Instance.DisposedTask; - DisposeComponents(); + await DisposeComponentsAsync(); - await wasDisposedTask.ShouldCompleteWithin(TimeSpan.FromSeconds(1)); + wasDisposedTask.Status.ShouldBe(TaskStatus.RanToCompletion); } [Fact(DisplayName = "DisposeComponents should dispose components added via ComponentFactory")] - public void Test203() + public async Task Test203() { ComponentFactories.Add(); var cut = Render(ps => ps.Add(p => p.CallStack, new List())); var instance = cut.FindComponent().Instance; - DisposeComponents(); + await DisposeComponentsAsync(); instance.WasDisposed.ShouldBeTrue(); } @@ -279,15 +275,13 @@ public void Dispose() WasDisposed = true; } } - - private sealed class AsyncThrowExceptionComponent : ComponentBase, IAsyncDisposable + + private sealed class AsyncThrowAfterDelayComponent : ComponentBase, IAsyncDisposable { - [Parameter] - public Task DisposedTask { get; set; } - public async ValueTask DisposeAsync() { - await DisposedTask; + await Task.Delay(1); + throw new NotSupportedException(); } } From a2b268e99e9a6ef339b4d2cff39840c4c475dc9a Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Thu, 14 Mar 2024 14:11:02 +0100 Subject: [PATCH 032/100] fix: Use correct version of packages for net9.0 --- src/bunit/bunit.csproj | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/bunit/bunit.csproj b/src/bunit/bunit.csproj index d15940429..e59bdd819 100644 --- a/src/bunit/bunit.csproj +++ b/src/bunit/bunit.csproj @@ -28,7 +28,7 @@ - + @@ -43,6 +43,18 @@ + + + + + + + + + + + + From 330e7f30dccd52df8de5f6efdc083b45ee71208b Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Thu, 14 Mar 2024 14:13:46 +0100 Subject: [PATCH 033/100] chore: Update xunit.runner.visualstudio --- tests/bunit.web.query.tests/bunit.web.query.tests.csproj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 ee8a7d400..acb082308 100644 --- a/tests/bunit.web.query.tests/bunit.web.query.tests.csproj +++ b/tests/bunit.web.query.tests/bunit.web.query.tests.csproj @@ -14,8 +14,7 @@ - - + all runtime; build; native; contentfiles; analyzers NU1701 From d2278b0d7db48cd89e29b1a05613536f28479bf8 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Fri, 22 Mar 2024 15:29:40 +0100 Subject: [PATCH 034/100] fix: Fixes after merge --- CHANGELOG.md | 2 +- MIGRATION.md | 4 +- docs/site/docs/verification/verify-markup.md | 20 ++++----- .../Web.AngleSharp/WrapperElementGenerator.cs | 2 +- .../ByLabelTextElementFactory.cs | 4 +- .../Labels/LabelQueryExtensions.cs | 6 +-- .../Strategies/ILabelTextQueryStrategy.cs | 2 +- .../LabelTextUsingAriaLabelStrategy.cs | 2 +- .../LabelTextUsingAriaLabelledByStrategy.cs | 2 +- .../LabelTextUsingForAttributeStrategy.cs | 2 +- .../LabelTextUsingWrappedElementStrategy.cs | 2 +- src/bunit.web.query/bunit.web.query.csproj | 2 +- .../Labels/LabelQueryExtensionsTests.cs | 42 +++++++++---------- 13 files changed, 46 insertions(+), 46 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 781da071e..e2f7fb944 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -676,7 +676,7 @@ List of new features. - Added `Render(RenderFragment)` and `Render(RenderFragment)` methods to `TestContext`, as well as various overloads to the `MarkupMatches` methods, that also takes a `RenderFragment` as the expected value. - The difference between the generic `Render` method and the non-generic one is that the generic returns an `IRenderedComponent`, whereas the non-generic one returns a `IRenderedFragment`. + The difference between the generic `Render` method and the non-generic one is that the generic returns an `IRenderedComponent`, whereas the non-generic one returns a `RenderedFragment`. Calling `Render(RenderFragent)` is equivalent to calling `Render(RenderFragment).FindComponent()`, e.g. it returns the first component in the render tree of type `TComponent`. This is different from the `RenderComponent()` method, where `TComponent` _is_ the root component of the render tree. diff --git a/MIGRATION.md b/MIGRATION.md index 275a9c313..02f944288 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -4,7 +4,7 @@ This document describes the changes that need to be made to migrate from bUnit 1 ## Removal of `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods The `GetChangesSinceFirstRender` and `GetChangesSinceLastRender` methods have been removed from `RenderedComponent`. There is no one-to-one replacement for these methods, but the general idea is to select the HTML in question via `Find` and assert against that. -Alternatively, the `IRenderedFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. +Alternatively, the `RenderedFragment` still offers the `OnMarkupUpdated` event, which can be used to assert against the markup after a render. ## Removal of `IsNullOrEmpty` extension method on `IEnumerable` and `CreateLogger` on `IServiceProvider` The `IsNullOrEmpty` extension method on `IEnumerable` has been removed, as well as the `CreateLogger` extension method on `IServiceProvider`. These extension methods are pretty common and conflict with other libraries. These methods can be recreated like this: @@ -29,7 +29,7 @@ The `bunit.core` and `bunit.web` packages have been merged into a single `bunit` ## Removal of unneeded abstraction ### `IRenderedComponentBase` and `RenderedFragmentBase` -`IRenderedComponentBase`, `IRenderedComponent`, `IRenderedFragmentBase`, `IRenderedFragment` and `RenderedFragmentBase` have been removed. +`IRenderedComponentBase`, `IRenderedComponent`, `RenderedFragmentBase`, `RenderedFragment` and `RenderedFragmentBase` have been removed. If you used either of these types, you should replace them with `RenderedComponent` or `RenderedFragment` respectively. ### `WebTestRender` merged into `BunitTestRender` diff --git a/docs/site/docs/verification/verify-markup.md b/docs/site/docs/verification/verify-markup.md index 147777e2e..4f6d4b1e6 100644 --- a/docs/site/docs/verification/verify-markup.md +++ b/docs/site/docs/verification/verify-markup.md @@ -22,24 +22,24 @@ The following sections will cover each of these. ## Result of rendering components -When a component is rendered in a test, the result is a or a . Through these, it is possible to access the rendered markup (HTML) of the component and, in the case of , the instance of the component. +When a component is rendered in a test, the result is a or a . Through these, it is possible to access the rendered markup (HTML) of the component and, in the case of , the instance of the component. > [!NOTE] > An inherits from . This page will only cover features of the type. is covered on the page. ## Inspecting DOM nodes -The rendered markup from a component is available as a DOM node through the property on . The nodes and element types comes from [AngleSharp](https://anglesharp.github.io/) that follows the W3C DOM API specifications and gives you the same results as a state-of-the-art browser’s implementation of the DOM API in JavaScript. Besides the official DOM API, AngleSharp and bUnit add some useful extension methods on top. This makes working with DOM nodes convenient. +The rendered markup from a component is available as a DOM node through the property on . The nodes and element types comes from [AngleSharp](https://anglesharp.github.io/) that follows the W3C DOM API specifications and gives you the same results as a state-of-the-art browser’s implementation of the DOM API in JavaScript. Besides the official DOM API, AngleSharp and bUnit add some useful extension methods on top. This makes working with DOM nodes convenient. ### Finding DOM elements bUnit supports multiple different ways of searching and querying the rendered HTML elements: - `FindByLabelText(string labelText)` that takes a text string used to label an input element and returns an `IElement` as output, or throws an exception if none are found (this is included in the experimental library [bunit.web.query](https://www.nuget.org/packages/bunit.web.query)). Use this method when possible compared to the generic `Find` and `FindAll` methods. -- [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) takes a "CSS selector" as input and returns an `IElement` as output, or throws an exception if none are found. -- [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) takes a "CSS selector" as input and returns a list of `IElement` elements. +- [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.RenderedFragment,System.String)) takes a "CSS selector" as input and returns an `IElement` as output, or throws an exception if none are found. +- [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.RenderedFragment,System.String,System.Boolean)) takes a "CSS selector" as input and returns a list of `IElement` elements. -Let's see some examples of using the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) and [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) methods to query the `` component listed below. +Let's see some examples of using the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.RenderedFragment,System.String)) and [`FindAll(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.RenderedFragment,System.String,System.Boolean)) methods to query the `` component listed below. [!code-razor[FancyTable.razor](../../../samples/components/FancyTable.razor)] @@ -53,15 +53,15 @@ Once you have one or more elements, you verify against them, such as by inspec #### Auto-refreshing Find() queries -An element found with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method will be updated if the component it came from is re-rendered. +An element found with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.RenderedFragment,System.String)) method will be updated if the component it came from is re-rendered. -However, that does not apply to elements that are found by traversing the DOM tree via the property on , for example, as those nodes do not know when their root component is re-rendered. Consequently, they don’t know when they should be updated. +However, that does not apply to elements that are found by traversing the DOM tree via the property on , for example, as those nodes do not know when their root component is re-rendered. Consequently, they don’t know when they should be updated. -As a result of this, it is always recommended to use the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.IRenderedFragment,System.String)) method when searching for a single element. Alternatively, always reissue the query whenever you need the element. +As a result of this, it is always recommended to use the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.RenderedFragment,System.String)) method when searching for a single element. Alternatively, always reissue the query whenever you need the element. #### Auto-refreshable FindAll() queries -The [`FindAll(string cssSelector, bool enableAutoRefresh = false)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.IRenderedFragment,System.String,System.Boolean)) method has an optional parameter, `enableAutoRefresh`, which when set to `true` will return a collection of `IElement`. This automatically refreshes itself when the component the elements came from is re-rendered. +The [`FindAll(string cssSelector, bool enableAutoRefresh = false)`](xref:Bunit.RenderedFragmentExtensions.FindAll(Bunit.RenderedFragment,System.String,System.Boolean)) method has an optional parameter, `enableAutoRefresh`, which when set to `true` will return a collection of `IElement`. This automatically refreshes itself when the component the elements came from is re-rendered. ## Semantic comparison of markup @@ -122,7 +122,7 @@ Learn more about the customization options on the property on . This holds the *raw* HTML from the component as a `string`. +To access the rendered markup of a component, just use the property on . This holds the *raw* HTML from the component as a `string`. > [!WARNING] > Be aware that all indentions and whitespace in your components (`.razor` files) are included in the raw rendered markup, so it is often wise to normalize the markup string a little. For example, via the string `Trim()` method to make the tests more stable. Otherwise, a change to the formatting in your components might break the tests unnecessarily when it does not need to. diff --git a/src/bunit.generators.internal/Web.AngleSharp/WrapperElementGenerator.cs b/src/bunit.generators.internal/Web.AngleSharp/WrapperElementGenerator.cs index b8b294e0a..ddbbd8db2 100644 --- a/src/bunit.generators.internal/Web.AngleSharp/WrapperElementGenerator.cs +++ b/src/bunit.generators.internal/Web.AngleSharp/WrapperElementGenerator.cs @@ -64,7 +64,7 @@ private static void GenerateOrdinaryMethod(StringBuilder source, IMethodSymbol m var methodParts = method.ToDisplayParts(GeneratorConfig.SymbolFormat); // It seems that the ToDisplayParts will return ... - // + // // public global::AngleSharp.Dom.IShadowRoot AttachShadow(global::AngleSharp.Dom.ShadowRootMode mode = 0) // // when called on a method with a default enum parameters specified. diff --git a/src/bunit.web.query/ByLabelTextElementFactory.cs b/src/bunit.web.query/ByLabelTextElementFactory.cs index eef786319..ca5cb63f8 100644 --- a/src/bunit.web.query/ByLabelTextElementFactory.cs +++ b/src/bunit.web.query/ByLabelTextElementFactory.cs @@ -5,13 +5,13 @@ namespace Bunit; internal sealed class ByLabelTextElementFactory : IElementWrapperFactory { - private readonly IRenderedFragment testTarget; + private readonly RenderedFragment testTarget; private readonly string labelText; private readonly ByLabelTextOptions options; public Action? OnElementReplaced { get; set; } - public ByLabelTextElementFactory(IRenderedFragment testTarget, string labelText, ByLabelTextOptions options) + public ByLabelTextElementFactory(RenderedFragment testTarget, string labelText, ByLabelTextOptions options) { this.testTarget = testTarget; this.labelText = labelText; diff --git a/src/bunit.web.query/Labels/LabelQueryExtensions.cs b/src/bunit.web.query/Labels/LabelQueryExtensions.cs index 8d7c42fad..7355987bc 100644 --- a/src/bunit.web.query/Labels/LabelQueryExtensions.cs +++ b/src/bunit.web.query/Labels/LabelQueryExtensions.cs @@ -4,7 +4,7 @@ namespace Bunit; /// -/// Extension methods for querying IRenderedFragments by Label +/// Extension methods for querying RenderedFragments by Label /// public static class LabelQueryExtensions { @@ -23,7 +23,7 @@ public static class LabelQueryExtensions /// The rendered fragment to search. /// The text of the label to search (i.e. the InnerText of the Label, such as "First Name" for a ``) /// Method used to override the default behavior of FindByLabelText. - public static IElement FindByLabelText(this IRenderedFragment renderedFragment, string labelText, Action? configureOptions = null) + public static IElement FindByLabelText(this RenderedFragment renderedFragment, string labelText, Action? configureOptions = null) { var options = ByLabelTextOptions.Default; if (configureOptions is not null) @@ -35,7 +35,7 @@ public static IElement FindByLabelText(this IRenderedFragment renderedFragment, return FindByLabelTextInternal(renderedFragment, labelText, options) ?? throw new LabelNotFoundException(labelText); } - internal static IElement? FindByLabelTextInternal(this IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) + internal static IElement? FindByLabelTextInternal(this RenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) { foreach (var strategy in LabelTextQueryStrategies) { diff --git a/src/bunit.web.query/Labels/Strategies/ILabelTextQueryStrategy.cs b/src/bunit.web.query/Labels/Strategies/ILabelTextQueryStrategy.cs index 3c1ba8ea5..64290af77 100644 --- a/src/bunit.web.query/Labels/Strategies/ILabelTextQueryStrategy.cs +++ b/src/bunit.web.query/Labels/Strategies/ILabelTextQueryStrategy.cs @@ -4,5 +4,5 @@ namespace Bunit.Labels.Strategies; internal interface ILabelTextQueryStrategy { - IElement? FindElement(IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options); + IElement? FindElement(RenderedFragment renderedFragment, string labelText, ByLabelTextOptions options); } diff --git a/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelStrategy.cs b/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelStrategy.cs index 2ef029809..6db805f36 100644 --- a/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelStrategy.cs +++ b/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelStrategy.cs @@ -5,7 +5,7 @@ namespace Bunit.Labels.Strategies; internal sealed class LabelTextUsingAriaLabelStrategy : ILabelTextQueryStrategy { - public IElement? FindElement(IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) + public IElement? FindElement(RenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) { var caseSensitivityQualifier = options.ComparisonType switch { diff --git a/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelledByStrategy.cs b/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelledByStrategy.cs index 3c81e47ac..8364c7454 100644 --- a/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelledByStrategy.cs +++ b/src/bunit.web.query/Labels/Strategies/LabelTextUsingAriaLabelledByStrategy.cs @@ -5,7 +5,7 @@ namespace Bunit.Labels.Strategies; internal sealed class LabelTextUsingAriaLabelledByStrategy : ILabelTextQueryStrategy { - public IElement? FindElement(IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) + public IElement? FindElement(RenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) { var elementsWithAriaLabelledBy = renderedFragment.Nodes.TryQuerySelectorAll("[aria-labelledby]"); diff --git a/src/bunit.web.query/Labels/Strategies/LabelTextUsingForAttributeStrategy.cs b/src/bunit.web.query/Labels/Strategies/LabelTextUsingForAttributeStrategy.cs index af3eb91f8..1b02afe5c 100644 --- a/src/bunit.web.query/Labels/Strategies/LabelTextUsingForAttributeStrategy.cs +++ b/src/bunit.web.query/Labels/Strategies/LabelTextUsingForAttributeStrategy.cs @@ -5,7 +5,7 @@ namespace Bunit.Labels.Strategies; internal sealed class LabelTextUsingForAttributeStrategy : ILabelTextQueryStrategy { - public IElement? FindElement(IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) + public IElement? FindElement(RenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) { var matchingLabel = renderedFragment.Nodes.TryQuerySelectorAll("label") .SingleOrDefault(l => l.TextContent.Trim().Equals(labelText, options.ComparisonType)); diff --git a/src/bunit.web.query/Labels/Strategies/LabelTextUsingWrappedElementStrategy.cs b/src/bunit.web.query/Labels/Strategies/LabelTextUsingWrappedElementStrategy.cs index 43f47503c..67ecff9a7 100644 --- a/src/bunit.web.query/Labels/Strategies/LabelTextUsingWrappedElementStrategy.cs +++ b/src/bunit.web.query/Labels/Strategies/LabelTextUsingWrappedElementStrategy.cs @@ -5,7 +5,7 @@ namespace Bunit.Labels.Strategies; internal sealed class LabelTextUsingWrappedElementStrategy : ILabelTextQueryStrategy { - public IElement? FindElement(IRenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) + public IElement? FindElement(RenderedFragment renderedFragment, string labelText, ByLabelTextOptions options) { var matchingLabel = renderedFragment.Nodes.TryQuerySelectorAll("label") .SingleOrDefault(l => l.GetInnerText().Trim().StartsWith(labelText, options.ComparisonType)); diff --git a/src/bunit.web.query/bunit.web.query.csproj b/src/bunit.web.query/bunit.web.query.csproj index 0fded8cba..c4ef80695 100644 --- a/src/bunit.web.query/bunit.web.query.csproj +++ b/src/bunit.web.query/bunit.web.query.csproj @@ -27,7 +27,7 @@ - + diff --git a/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs b/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs index 9ee2c2e6c..f4c3a5d4c 100644 --- a/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs +++ b/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs @@ -2,7 +2,7 @@ namespace Bunit.Labels; -public class LabelQueryExtensionsTests : TestContext +public class LabelQueryExtensionsTests : BunitContext { public static TheoryData HtmlElementsThatCanHaveALabel { get; } = new() { @@ -19,7 +19,7 @@ public class LabelQueryExtensionsTests : TestContext public void Test001(string htmlElementWithLabel) { var labelText = $"Label for {htmlElementWithLabel} 1"; - var cut = RenderComponent(ps => + var cut = Render(ps => ps.AddChildContent($""" <{htmlElementWithLabel} id="{htmlElementWithLabel}-with-label" /> @@ -36,7 +36,7 @@ public void Test001(string htmlElementWithLabel) public void Test002() { var expectedLabelText = Guid.NewGuid().ToString(); - var cut = RenderComponent(ps => + var cut = Render(ps => ps.AddChildContent($""" {Guid.NewGuid()} """)); @@ -50,7 +50,7 @@ public void Test002() public void Test003(string htmlElementWithLabel) { var labelText = $"{htmlElementWithLabel} Wrapped Label"; - var cut = RenderComponent(ps => + var cut = Render(ps => ps.AddChildContent($""" /// The markup to parse. /// The . - public INodeList Parse([StringSyntax("Html")]string markup) + public INodeList Parse([StringSyntax("Html")] string markup) { ArgumentNullException.ThrowIfNull(markup); @@ -70,7 +70,7 @@ public INodeList Parse([StringSyntax("Html")]string markup) : htmlParser.ParseFragment(markup, ctx!); } - private SingleNodeNodeList ParseSpecial(string markup, string matchedElement) + private INodeList ParseSpecial(string markup, string matchedElement) { var doc = htmlParser.ParseDocument(markup); diff --git a/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs b/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs index 1171bd768..e94acdd85 100644 --- a/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs +++ b/tests/bunit.testassets/SampleComponents/PersistentComponentStateSample.razor.cs @@ -1,27 +1,21 @@ -namespace Bunit.TestAssets.SampleComponents +namespace Bunit.TestAssets.SampleComponents; + +public partial class PersistentComponentStateSample : ComponentBase { - public partial class PersistentComponentStateSample - { - public const string PersistenceKey = "fetchdata"; + public const string PersistenceKey = "fetchdata"; - public WeatherForecast[] Forecasts { get; private set; } + public WeatherForecast[] Forecasts { get; private set; } - [Inject] public PersistentComponentState State { get; set; } + [Inject] public PersistentComponentState State { get; set; } - protected override void OnInitialized() + protected override void OnInitialized() + { + State.RegisterOnPersisting(PersistForecasts); + if (!State.TryTakeFromJson(PersistenceKey, out var data)) { - State.RegisterOnPersisting(PersistForecasts); - if (!State.TryTakeFromJson(PersistenceKey, out var data)) - { - Forecasts = CreateForecasts(); - } - else - { - Forecasts = data; - } + Forecasts = CreateForecasts(); } - - private Task PersistForecasts() + else { State.PersistAsJson(PersistenceKey, Forecasts); return Task.CompletedTask; @@ -36,8 +30,22 @@ private WeatherForecast[] CreateForecasts() } } - public record class WeatherForecast + private Task PersistForecasts() { - public int Temperature { get; set; } + State.PersistAsJson(PersistenceKey, Forecasts); + return Task.CompletedTask; } + + private WeatherForecast[] CreateForecasts() + { + return new WeatherForecast[] + { + new WeatherForecast{ Temperature = 42 }, + }; + } +} + +public record class WeatherForecast +{ + public int Temperature { get; set; } } diff --git a/tests/bunit.tests/BunitContextTest.cs b/tests/bunit.tests/BunitContextTest.cs index a651cc44b..38669ea65 100644 --- a/tests/bunit.tests/BunitContextTest.cs +++ b/tests/bunit.tests/BunitContextTest.cs @@ -275,7 +275,7 @@ public void Dispose() WasDisposed = true; } } - + private sealed class AsyncThrowAfterDelayComponent : ComponentBase, IAsyncDisposable { public async ValueTask DisposeAsync() diff --git a/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs b/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs index f4c3a5d4c..856aa1721 100644 --- a/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs +++ b/tests/bunit.web.query.tests/Labels/LabelQueryExtensionsTests.cs @@ -135,7 +135,7 @@ public void Test007(string labelText) public void Test009(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""""")); Should.Throw(() => cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison)) @@ -149,7 +149,7 @@ public void Test009(StringComparison comparison) public void Test010(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""""")); var input = cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison); @@ -166,7 +166,7 @@ public void Test010(StringComparison comparison) public void Test011(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""""")); Should.Throw(() => cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison)) @@ -180,7 +180,7 @@ public void Test011(StringComparison comparison) public void Test012(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""""")); var input = cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison); @@ -197,7 +197,7 @@ public void Test012(StringComparison comparison) public void Test013(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""""")); Should.Throw(() => cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison)) @@ -211,7 +211,7 @@ public void Test013(StringComparison comparison) public void Test014(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""""")); var input = cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison); @@ -228,7 +228,7 @@ public void Test014(StringComparison comparison) public void Test015(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""

    Label Text

    """)); Should.Throw(() => cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison)) @@ -242,7 +242,7 @@ public void Test015(StringComparison comparison) public void Test016(StringComparison comparison) { var expectedLabelText = "LABEL TEXT"; - var cut = Render(ps => + var cut = Render(ps => ps.AddChildContent("""

    Label Text

    """)); var input = cut.FindByLabelText(expectedLabelText, o => o.ComparisonType = comparison); From c375196b0dfc21c6bdbdc02f5c4457b1a28e2834 Mon Sep 17 00:00:00 2001 From: Egil Hansen Date: Fri, 12 Apr 2024 17:06:43 +0000 Subject: [PATCH 036/100] fix: docs samples csproj --- docs/samples/components/bunit.docs.samples.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/samples/components/bunit.docs.samples.csproj b/docs/samples/components/bunit.docs.samples.csproj index 248c2e787..4617a87b1 100644 --- a/docs/samples/components/bunit.docs.samples.csproj +++ b/docs/samples/components/bunit.docs.samples.csproj @@ -1,7 +1,7 @@ - net8.0;net.9.0 + net8.0;net9.0 Bunit.Docs.Samples enable CA1014,NU5104 From 3cf2b79e4351aca119edd3ef6f901b14552ee6a4 Mon Sep 17 00:00:00 2001 From: Steven Giesel Date: Sat, 13 Apr 2024 12:46:10 +0200 Subject: [PATCH 037/100] refactor: Merge RenderedFragment and RenderedComponent into IRenderedComponent with single internal RenderedComponent type * refactor: Merge RenderedFragment and RenderedComponent into IRenderedComponent * fix: use generic parameters correctly * revert: rename BunitRootComponent to ContainerFragment * refactor: rename RootComponent to BunitRootComponent --------- Co-authored-by: Egil Hansen --- .editorconfig | 1 + docs/samples/tests/xunit/ReRenderTest.cs | 2 +- .../docs/interaction/awaiting-async-state.md | 4 +- .../docs/interaction/dispose-components.md | 2 +- .../interaction/trigger-event-handlers.md | 4 +- docs/site/docs/interaction/trigger-renders.md | 22 +-- .../passing-parameters-to-components.md | 2 +- .../site/docs/verification/async-assertion.md | 4 +- .../verification/verify-component-state.md | 16 +- docs/site/docs/verification/verify-markup.md | 26 +-- .../ByLabelTextElementFactory.cs | 4 +- .../Labels/LabelQueryExtensions.cs | 12 +- .../Strategies/ILabelTextQueryStrategy.cs | 2 +- .../LabelTextUsingAriaLabelStrategy.cs | 6 +- .../LabelTextUsingAriaLabelledByStrategy.cs | 8 +- .../LabelTextUsingForAttributeStrategy.cs | 8 +- .../LabelTextUsingWrappedElementStrategy.cs | 6 +- src/bunit/Asserting/CompareToExtensions.cs | 13 +- .../MarkupMatchesAssertExtensions.cs | 61 +++--- src/bunit/BunitContext.Obsoletes.cs | 4 +- src/bunit/BunitContext.cs | 24 +-- .../Extensions/BunitRendererExtensions.cs | 6 +- .../IRefreshableElementCollection.cs | 4 +- .../InputFile/InputFileExtensions.cs | 2 +- .../Internal/CssSelectorElementFactory.cs | 4 +- .../Internal/RefreshableElementCollection.cs | 14 +- .../Extensions/RenderedComponentExtensions.cs | 90 +++++++++ ...RenderedComponentInvokeAsyncExtensions.cs} | 40 ++-- .../RenderedComponentRenderExtensions.cs | 4 +- .../Extensions/RenderedFragmentExtensions.cs | 88 --------- ...WaitForHelperExtensions.WaitForElement.cs} | 130 +++++++------ ...ntWaitForHelperExtensions.WaitForState.cs} | 38 ++-- .../WaitForHelpers/WaitForAssertionHelper.cs | 13 +- .../WaitForHelpers/WaitForElementHelper.cs | 9 +- .../WaitForHelpers/WaitForElementsHelper.cs | 9 +- .../WaitForHelpers/WaitForFailedException.cs | 6 +- .../WaitForHelpers/WaitForHelper.cs | 43 +++-- .../WaitForHelperLoggerExtensions.cs | 12 +- .../WaitForHelpers/WaitForStateHelper.cs | 13 +- .../Rendering/BunitComponentActivator.cs | 4 +- src/bunit/Rendering/BunitRenderer.cs | 31 +-- ...mentContainer.cs => BunitRootComponent.cs} | 10 +- .../Rendering/ComponentDisposedException.cs | 2 +- src/bunit/Rendering/IRenderedComponent.cs | 77 ++++++++ src/bunit/Rendering/RenderEvent.cs | 3 +- src/bunit/Rendering/RenderedComponent.cs | 180 +++++++++++++----- src/bunit/Rendering/RenderedFragment.cs | 180 ------------------ src/bunit/Rendering/RootComponent.cs | 6 +- .../CompareToDiffingExtensionsBunit.cs | 78 -------- .../CompareToDiffingExtensionsTest.cs | 43 +++++ ...s => MarkupMatchesAssertExtensionsTest.cs} | 36 ++-- ...hesTests.razor => MarkupMatchesTest.razor} | 0 ...ringBunit.cs => ComponentRenderingTest.cs} | 4 +- ....cs => ConditionalComponentFactoryTest.cs} | 2 +- ...unit.cs => GenericComponentFactoryTest.cs} | 2 +- ...nit.cs => InstanceComponentFactoryTest.cs} | 2 +- ...ryBunit.cs => StubComponentFactoryTest.cs} | 2 +- ...mponentParameterCollectionBuilderTests.cs} | 7 +- ...nentParameterCollectionBuilderTests.razor} | 0 .../ComponentParameterCollectionBunit.cs | 2 +- ...> ClipboardEventDispatchExtensionsTest.cs} | 4 +- ...lsElementEventDispatcherExtensionsTest.cs} | 2 +- ....cs => DragEventDispatchExtensionsTest.cs} | 4 +- ...unit.cs => EventDispatchExtensionsTest.cs} | 4 +- ...cs => FocusEventDispatchExtensionsTest.cs} | 4 +- ... => GeneralEventDispatchExtensionsTest.cs} | 4 +- ...cs => InputEventDispatchExtensionsTest.cs} | 4 +- ...=> KeyboardEventDispatchExtensionsTest.cs} | 4 +- ...cs => MediaEventDispatchExtensionsTest.cs} | 4 +- ...cs => MouseEventDispatchExtensionsTest.cs} | 4 +- ... => PointerEventDispatchExtensionsTest.cs} | 4 +- ...=> ProgressEventDispatchExtensionsTest.cs} | 4 +- ...cs => TouchEventDispatchExtensionsTest.cs} | 4 +- .../TriggerEventSpy.cs | 4 +- ...cs => WheelEventDispatchExtensionsTest.cs} | 4 +- .../{InputFileBunits.cs => InputFileTest.cs} | 4 +- ....cs => RefreshableQueryCollectionTests.cs} | 2 +- ...it.cs => RefreshingWrappedElementTests.cs} | 2 +- ...RenderedComponentRenderExtensionsTests.cs} | 2 +- ...ntWaitForElementsHelperExtensions.Test.cs} | 10 +- ...ntWaitForElementsHelperExtensionsBunit.cs} | 10 +- ...nderedComponentWaitForHelperExtensions.cs} | 10 +- ...unit.cs => BunitComponentActivatorTest.cs} | 2 +- .../Rendering/BunitRendererBunits.cs | 2 +- .../Rendering/RenderedComponentBunit.cs | 60 ------ ...gmentBunit.cs => RenderedComponentTest.cs} | 61 +++++- ...nderTreeBunit.cs => RootRenderTreeTest.cs} | 2 +- ...orizationBunit.cs => AuthorizationTest.cs} | 4 +- ...=> BunitSignOutSessionStateManagerTest.cs} | 2 +- ...=> BunitWebAssemblyHostEnvironmentTest.cs} | 2 +- ...aseBunit.cs => ComponentDoubleBaseTest.cs} | 2 +- ...Bunit.cs => BunitNavigationManagerTest.cs} | 2 +- ...s => BunitPersistentComponentStateTest.cs} | 4 +- .../TestUtilities/MockingHelpers.cs | 70 ------- 94 files changed, 826 insertions(+), 912 deletions(-) create mode 100644 src/bunit/Extensions/RenderedComponentExtensions.cs rename src/bunit/Extensions/{RenderedFragmentInvokeAsyncExtensions.cs => RenderedComponentInvokeAsyncExtensions.cs} (58%) delete mode 100644 src/bunit/Extensions/RenderedFragmentExtensions.cs rename src/bunit/Extensions/WaitForHelpers/{RenderedFragmentWaitForHelperExtensions.WaitForElement.cs => RenderedComponentWaitForHelperExtensions.WaitForElement.cs} (58%) rename src/bunit/Extensions/WaitForHelpers/{RenderedFragmentWaitForHelperExtensions.WaitForState.cs => RenderedComponentWaitForHelperExtensions.WaitForState.cs} (65%) rename src/bunit/Rendering/{FragmentContainer.cs => BunitRootComponent.cs} (82%) create mode 100644 src/bunit/Rendering/IRenderedComponent.cs delete mode 100644 src/bunit/Rendering/RenderedFragment.cs delete mode 100644 tests/bunit.tests/Asserting/CompareToDiffingExtensionsBunit.cs create mode 100644 tests/bunit.tests/Asserting/CompareToDiffingExtensionsTest.cs rename tests/bunit.tests/Asserting/{MarkupMatchesAssertExtensionsBunit.cs => MarkupMatchesAssertExtensionsTest.cs} (80%) rename tests/bunit.tests/Asserting/{MarkupMatchesTests.razor => MarkupMatchesTest.razor} (100%) rename tests/bunit.tests/BlazorE2E/{ComponentRenderingBunit.cs => ComponentRenderingTest.cs} (99%) rename tests/bunit.tests/ComponentFactories/{ConditionalComponentFactoryBunit.cs => ConditionalComponentFactoryTest.cs} (97%) rename tests/bunit.tests/ComponentFactories/{GenericComponentFactoryBunit.cs => GenericComponentFactoryTest.cs} (95%) rename tests/bunit.tests/ComponentFactories/{InstanceComponentFactoryBunit.cs => InstanceComponentFactoryTest.cs} (96%) rename tests/bunit.tests/ComponentFactories/{StubComponentFactoryBunit.cs => StubComponentFactoryTest.cs} (98%) rename tests/bunit.tests/{ComponentParameterCollectionBuilderBunits.cs => ComponentParameterCollectionBuilderTests.cs} (98%) rename tests/bunit.tests/{ComponentParameterCollectionBuilderBunits.razor => ComponentParameterCollectionBuilderTests.razor} (100%) rename tests/bunit.tests/EventDispatchExtensions/{ClipboardEventDispatchExtensionsBunit.cs => ClipboardEventDispatchExtensionsTest.cs} (67%) rename tests/bunit.tests/EventDispatchExtensions/{DetailsElementEventDispatcherExtensionsBunit.cs => DetailsElementEventDispatcherExtensionsTest.cs} (80%) rename tests/bunit.tests/EventDispatchExtensions/{DragEventDispatchExtensionsBunit.cs => DragEventDispatchExtensionsTest.cs} (77%) rename tests/bunit.tests/EventDispatchExtensions/{EventDispatchExtensionsBunit.cs => EventDispatchExtensionsTest.cs} (96%) rename tests/bunit.tests/EventDispatchExtensions/{FocusEventDispatchExtensionsBunit.cs => FocusEventDispatchExtensionsTest.cs} (68%) rename tests/bunit.tests/EventDispatchExtensions/{GeneralEventDispatchExtensionsBunit.cs => GeneralEventDispatchExtensionsTest.cs} (98%) rename tests/bunit.tests/EventDispatchExtensions/{InputEventDispatchExtensionsBunit.cs => InputEventDispatchExtensionsTest.cs} (98%) rename tests/bunit.tests/EventDispatchExtensions/{KeyboardEventDispatchExtensionsBunit.cs => KeyboardEventDispatchExtensionsTest.cs} (95%) rename tests/bunit.tests/EventDispatchExtensions/{MediaEventDispatchExtensionsBunit.cs => MediaEventDispatchExtensionsTest.cs} (65%) rename tests/bunit.tests/EventDispatchExtensions/{MouseEventDispatchExtensionsBunit.cs => MouseEventDispatchExtensionsTest.cs} (92%) rename tests/bunit.tests/EventDispatchExtensions/{PointerEventDispatchExtensionsBunit.cs => PointerEventDispatchExtensionsTest.cs} (80%) rename tests/bunit.tests/EventDispatchExtensions/{ProgressEventDispatchExtensionsBunit.cs => ProgressEventDispatchExtensionsTest.cs} (70%) rename tests/bunit.tests/EventDispatchExtensions/{TouchEventDispatchExtensionsBunit.cs => TouchEventDispatchExtensionsTest.cs} (76%) rename tests/bunit.tests/EventDispatchExtensions/{WheelEventDispatchExtensionsBunit.cs => WheelEventDispatchExtensionsTest.cs} (80%) rename tests/bunit.tests/Extensions/InputFile/{InputFileBunits.cs => InputFileTest.cs} (97%) rename tests/bunit.tests/Extensions/{RefreshableQueryCollectionBunit.cs => RefreshableQueryCollectionTests.cs} (96%) rename tests/bunit.tests/Extensions/{RefreshingWrappedElementBunit.cs => RefreshingWrappedElementTests.cs} (97%) rename tests/bunit.tests/Extensions/{RenderedComponentRenderExtensionsBunit.cs => RenderedComponentRenderExtensionsTests.cs} (85%) rename tests/bunit.tests/Extensions/WaitForHelpers/{RenderedFragmentWaitForElementsHelperExtensions.Async.Test.cs => RenderedComponentWaitForElementsHelperExtensions.Test.cs} (87%) rename tests/bunit.tests/Extensions/WaitForHelpers/{RenderedFragmentWaitForElementsHelperExtensionsBunit.cs => RenderedComponentWaitForElementsHelperExtensionsBunit.cs} (86%) rename tests/bunit.tests/Extensions/WaitForHelpers/{RenderedFragmentWaitForHelperExtensionsBunit.cs => RenderedComponentWaitForHelperExtensions.cs} (91%) rename tests/bunit.tests/Rendering/{BunitComponentActivatorBunit.cs => BunitComponentActivatorTest.cs} (96%) delete mode 100644 tests/bunit.tests/Rendering/RenderedComponentBunit.cs rename tests/bunit.tests/Rendering/{RenderedFragmentBunit.cs => RenderedComponentTest.cs} (71%) rename tests/bunit.tests/Rendering/{RootRenderTreeBunit.cs => RootRenderTreeTest.cs} (99%) rename tests/bunit.tests/TestDoubles/Authorization/{AuthorizationBunit.cs => AuthorizationTest.cs} (98%) rename tests/bunit.tests/TestDoubles/{BunitSignOutSessionStateManagerBunit.cs => BunitSignOutSessionStateManagerTest.cs} (91%) rename tests/bunit.tests/TestDoubles/{BunitWebAssemblyHostEnvironmentBunit.cs => BunitWebAssemblyHostEnvironmentTest.cs} (92%) rename tests/bunit.tests/TestDoubles/Components/{ComponentDoubleBaseBunit.cs => ComponentDoubleBaseTest.cs} (89%) rename tests/bunit.tests/TestDoubles/NavigationManager/{BunitNavigationManagerBunit.cs => BunitNavigationManagerTest.cs} (99%) rename tests/bunit.tests/TestDoubles/PersistentComponentState/{BunitPersistentComponentStateBunit.cs => BunitPersistentComponentStateTest.cs} (93%) delete mode 100644 tests/bunit.tests/TestUtilities/MockingHelpers.cs diff --git a/.editorconfig b/.editorconfig index 5472a756f..4c989e4aa 100644 --- a/.editorconfig +++ b/.editorconfig @@ -453,6 +453,7 @@ dotnet_diagnostic.S112.severity = none # S112: General exceptions should never b dotnet_diagnostic.S1075.severity = suggestion # S1075: URIs should not be hardcoded dotnet_diagnostic.S1186.severity = suggestion # S1186: Methods should not be empty dotnet_diagnostic.S2292.severity = suggestion # S2292: Trivial properties should be auto-implemented +dotnet_diagnostic.S2743.severity = suggestion # S2743: A static field in a generic type is not shared among instances dotnet_diagnostic.S4158.severity = none # BUGGY with C#9 code - doesnt understand local methods # Razor specific rules diff --git a/docs/samples/tests/xunit/ReRenderTest.cs b/docs/samples/tests/xunit/ReRenderTest.cs index 6684ac8b4..0dc6d5f01 100644 --- a/docs/samples/tests/xunit/ReRenderTest.cs +++ b/docs/samples/tests/xunit/ReRenderTest.cs @@ -73,7 +73,7 @@ public async Task RendersViaInvokeAsyncWithLoading() // Indirectly re-renders and returns the task returned by Calculate(). // The explicit here is important, otherwise the call to Calculate() // will be awaited automatically. - var task = await cut.InvokeAsync(() => cut.Instance.Calculate(1, 2)); + var task = await cut.InvokeAsync(() => cut.Instance.Calculate(1, 2)); cut.MarkupMatches("Loading"); // Wait for the task to complete. diff --git a/docs/site/docs/interaction/awaiting-async-state.md b/docs/site/docs/interaction/awaiting-async-state.md index e26d62183..88f6836fb 100644 --- a/docs/site/docs/interaction/awaiting-async-state.md +++ b/docs/site/docs/interaction/awaiting-async-state.md @@ -9,13 +9,13 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{System.TimeSpan})) method covered on the page. +bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForState``1(Bunit.IRenderedComponent{``0},System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForAssertion``1(Bunit.IRenderedComponent{``0},System.Action,System.Nullable{System.TimeSpan})) method covered on the page. Let's start by taking a look at the `WaitForState` method in more detail. ## Waiting for state using `WaitForState` -The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) +The [`WaitForState(Func, TimeSpan?)`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForState``1(Bunit.IRenderedComponent{``0},System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method can be used to block and wait in a test method, until the provided predicate returns true or the timeout is reached. (The default timeout is one second.) > [!NOTE] > The `WaitForState()` method will try the predicate passed to it when the `WaitForState()` method is called, and every time the component under test renders. diff --git a/docs/site/docs/interaction/dispose-components.md b/docs/site/docs/interaction/dispose-components.md index 916ed5a61..6b22fb465 100644 --- a/docs/site/docs/interaction/dispose-components.md +++ b/docs/site/docs/interaction/dispose-components.md @@ -13,7 +13,7 @@ The following example of this: [!code-csharp[DisposeComponentsTest.cs](../../../samples/tests/xunit/DisposeComponentsTest.cs#L13-L22)] > [!WARNING] -> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForState(Bunit.RenderedFragment,System.Func{System.Boolean},System.Nullable{System.TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedFragmentWaitForHelperExtensions.WaitForAssertion(Bunit.RenderedFragment,System.Action,System.Nullable{System.TimeSpan})) will not work as a disposed component will not trigger a new render cycle. +> For `IAsyncDisposable` (since .net5) relying on [`WaitForState()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForState``1(Bunit.IRenderedComponent{``0},System.Func{System.Boolean},System.Nullable{System.TimeSpan})) or [`WaitForAssertion()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForAssertion``1(Bunit.IRenderedComponent{``0},System.Action,System.Nullable{System.TimeSpan})) will not work as a disposed component will not trigger a new render cycle. ## Disposing components asynchronously If a component implements `IAsyncDisposable`, `DisposeComponentsAsync` can be awaited to wait for all asynchronous `DisposeAsync` methods. Sometimes interacting with JavaScript in Blazor WebAssembly requires disposing or resetting state in `DisposeAsync`. diff --git a/docs/site/docs/interaction/trigger-event-handlers.md b/docs/site/docs/interaction/trigger-event-handlers.md index f030ed4f5..dec219d43 100644 --- a/docs/site/docs/interaction/trigger-event-handlers.md +++ b/docs/site/docs/interaction/trigger-event-handlers.md @@ -23,7 +23,7 @@ bUnit comes with event dispatch helper methods that makes it possible to invoke - [Progress events](xref:Bunit.ProgressEventDispatchExtensions) - [Touch event](xref:Bunit.TouchEventDispatchExtensions) -To use these, first find the element in the component under test where the event handler is bound. This is usually done with the [`Find(string cssSelector)`](xref:Bunit.RenderedFragmentExtensions.Find(Bunit.RenderedFragment,System.String)) method. Next, invoke the event dispatch helper method of choice. +To use these, first find the element in the component under test where the event handler is bound. This is usually done with the [`Find(string cssSelector)`](xref:Bunit.RenderedComponentExtensions.Find``1(Bunit.IRenderedComponent{``0},System.String)) method. Next, invoke the event dispatch helper method of choice. The following section demonstrates how to do this... @@ -49,7 +49,7 @@ To trigger the `@onclick` `ClickHandler` event handler method in the `` This is what happens in the test: -1. In the arrange step of the test, the `` component is rendered and the `