Open Closed

"AbpBlazorMessageLocalizerHelper has not been registered" error when starting a Blazor test #7511


User avatar
0
PDarioJer created
  • ABP Framework version: v8.2.0
  • UI Type: Blazor Server
  • Database System: EF Core (SQL Server)
  • Tiered (for MVC) or Auth Server Separated (for Angular): no
  • Exception message and full stack trace:
Autofac.Core.Registration.ComponentNotRegisteredException: The requested service 'Volo.Abp.AspNetCore.Components.Web.AbpBlazorMessageLocalizerHelper`1...

Autofac.Core.Registration.ComponentNotRegisteredException
The requested service 'Volo.Abp.AspNetCore.Components.Web.AbpBlazorMessageLocalizerHelper`1[[DummyPlatform.Localization.DummyPlatformResource, DummyPlatform.Domain.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

See https://autofac.rtfd.io/help/service-not-registered for more info.
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType)
   at Autofac.Extensions.DependencyInjection.AutofacServiceProvider.GetRequiredService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Volo.Abp.AbpTestBaseWithServiceProvider.GetRequiredService[T]()
   at DummyPlatform.Blazor.Tests.Items.ItemPage_IntegrationShould.Load_Items() in C:\Users\user\source\repos\DummyPlatform\test\DummyPlatform.Blazor.Tests\Items\ItemPage_IntegrationShould.cs:line 22
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
   at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
  • Steps to reproduce the issue:
  • I followed the guide in Ma Liming's blogpost to create a test suite: https://community.abp.io/posts/how-to-test-blazor-components-in-abp-phcijx8e
  • However, it seems to have an issue with the LocalizerHelper. I tried to get the required service in my test but it didn't seem to work

Item.razor

@page "/items"
@using DummyPlatform.Items
@using DummyPlatform.Localization
@using Volo.Abp.AspNetCore.Components.Web
@inherits DummyPlatformComponentBase
@inject IItemAppService ItemAppService
@inject AbpBlazorMessageLocalizerHelper<DummyPlatformResource> LH
<Card>
    <CardHeader>
        <Row Class="justify-content-between">
            <Column ColumnSize="ColumnSize.IsAuto">
                <h2>@L["Items"]</h2>
            </Column>
        </Row>
    </CardHeader>
    <CardBody>
        <DataGrid TItem="ItemDto"
                  Data="ItemList"
                  ReadData="OnDataGridReadAsync"
                  TotalItems="TotalCount"
                  ShowPager="true"
                  PageSize="PageSize">
            <DataGridColumns>
                <DataGridColumn TItem="ItemDto"
                                Field="@nameof(ItemDto.ItemNr)"
                                Caption="@L["ItemNr"]"></DataGridColumn>
                <DataGridColumn TItem="ItemDto"
                                Field="@nameof(ItemDto.VariantCode)"
                                Caption="@L["VariantCode"]"></DataGridColumn>
                <DataGridColumn TItem="ItemDto"
                                Field="@nameof(ItemDto.Description)"
                                Caption="@L["Description"]"></DataGridColumn>
            </DataGridColumns>
        </DataGrid>
    </CardBody>
</Card>

<Modal @ref="ItemDetailModal">
    <_ModalBackdrop></_ModalBackdrop>
    <ModalContent IsCentered="true">
        <Form>
            <ModalHeader>
                <ModalTitle>@OpenedItem.ItemNr</ModalTitle>
                <CloseButton Clicked="CloseItemDetailModal"></CloseButton>
            </ModalHeader>
            <ModalBody>
                <Field>
                    <FieldLabel>@L["ItemNr"]</FieldLabel>
                    <TextEdit @bind-Text="@OpenedItem.ItemNr"></TextEdit>
                </Field>
                <Field>
                    <FieldLabel>@L["VariantCode"]</FieldLabel>
                    <TextEdit @bind-Text="@OpenedItem.ItemNr"></TextEdit>
                </Field>
                <Field>
                    <FieldLabel>@L["Description"]</FieldLabel>
                    <TextEdit @bind-Text="@OpenedItem.Description"></TextEdit>
                </Field>
            </ModalBody>
            <ModalFooter>
                <Button Color="Color.Secondary"
                        Clicked="CloseItemDetailModal">
                    @L["Cancel"]
                </Button>
            </ModalFooter>
        </Form>
    </ModalContent>
</Modal>

Unit Test

using DummyPlatform.Items;
using DummyPlatform.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using NSubstitute;
using Volo.Abp.AspNetCore.Components.Web;
using Xunit;

namespace DummyPlatform.Blazor.Tests.Items;

public class ItemPage_IntegrationShould : DummyPlatformBlazorTestBase
{
	private IItemAppService _itemAppService;
	private AbpBlazorMessageLocalizerHelper<DummyPlatformResource> _lh;
	
	[Fact]
	public void Load_Items()
	{
		// Arrange
		var ctx = CreateTestContext();
		_itemAppService = Substitute.For<IItemAppService>();
		_lh = GetRequiredService<AbpBlazorMessageLocalizerHelper<DummyPlatformResource>>();
		
		ctx.Services.AddSingleton(_itemAppService);
		ctx.Services.AddSingleton(_lh);
		
		// Act
		ctx.RenderComponent<DummyPlatform.Blazor.Pages.Items>();
		
		// Assert
		_itemAppService.Received(1).GetListAsync(Arg.Any<GetItemListDto>());
	}
}

I kept the Testbase the same as in the blogpost. As you can see, I kept very close to the Tutorial from the ABP documentation, so someone else could encounter the same problem. Do I maybe have a missing dependency here?


8 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    Can you fork this sample and add your code to reproduce the error?

    Thanks

    https://github.com/abpframework/abp-samples/tree/master/BlazorPageUniTest

  • User Avatar
    0
    PDarioJer created

    hi

    Can you fork this sample and add your code to reproduce the error?

    Thanks

    https://github.com/abpframework/abp-samples/tree/master/BlazorPageUniTest

    Hi,

    I added my code. It shows the same error as in my project https://github.com/PDarioJer/abp-samples

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    services.AddSingleton<AbpBlazorMessageLocalizerHelper<BookStoreResource>>();

    using BookStore.Localization;
    using Bunit;
    using Microsoft.Extensions.DependencyInjection;
    using Shouldly;
    using Volo.Abp.AspNetCore.Components.Web;
    using Xunit;
    
    namespace BookStore.Blazor.Tests;
    
    public class Index_Tests : BookStoreBlazorTestBase
    {
        protected override void AfterAddApplication(IServiceCollection services)
        {
            services.AddSingleton<AbpBlazorMessageLocalizerHelper<BookStoreResource>>();
            base.AfterAddApplication(services);
        }
    
        [Fact]
        public void Index_Test()
        {
            // Arrange
            var ctx = CreateTestContext();
            // var lh = GetRequiredService<AbpBlazorMessageLocalizerHelper<BookStoreResource>>();
            // ctx.Services.AddSingleton(lh);
    
            // Act
            var cut = ctx.RenderComponent<BookStore.Blazor.Pages.Index>();
    
    
            // Assert
            cut.Find(".lead").InnerHtml.Contains("Welcome to the application. This is a startup project based on the ABP framework. For more information, visit abp.io.").ShouldBeTrue();
            cut.Find("#username").InnerHtml.Contains("Welcome admin").ShouldBeTrue();
        }
    }
    
    
  • User Avatar
    0
    PDarioJer created

    Hi,

    while this worked to resolve the dependency, I encountered the following error when adding a form with a TextObject

    Bunit.JSRuntimeUnhandledInvocationException: bUnit's JSInterop has not been configured to handle the call:
    
    Bunit.JSRuntimeUnhandledInvocationException
    bUnit's JSInterop has not been configured to handle the call:
    
        InvokeVoidAsync("initialize", Microsoft.AspNetCore.Components.ElementReference, "0HN55GR2KUKHU", null, null)
    
    Configure bUnit's JSInterop to handle the call with following:
    
        SetupVoid("initialize", Microsoft.AspNetCore.Components.ElementReference, "0HN55GR2KUKHU", null, null)
    or the following, to match any arguments:
        SetupVoid("initialize", _ => true)
    
    The setup methods are available on an instance of the BunitJSInterop or
    BunitJSModuleInterop type. The standard BunitJSInterop is available
    through the TestContext.JSInterop property, and a BunitJSModuleInterop
    instance is returned from calling SetupModule on a BunitJSInterop instance.
    
       at Bunit.BunitJSInterop.TryHandlePlannedInvocation[TValue](JSRuntimeInvocation invocation) in /_/src/bunit.web/JSInterop/BunitJSInterop.cs:line 83
       at Bunit.BunitJSInterop.HandleInvocation[TValue](JSRuntimeInvocation invocation) in /_/src/bunit.web/JSInterop/BunitJSInterop.cs:line 68
       at Bunit.JSInterop.Implementation.JSRuntimeExtensions.HandleInvokeAsync[TValue](BunitJSInterop jSInterop, String identifier, Object[] args) in /_/src/bunit.web/JSInterop/Implementation/JSRuntimeExtensions.cs:line 9
       at Bunit.BunitJSObjectReference.InvokeAsync[TValue](String identifier, Object[] args) in /_/src/bunit.web/JSInterop/Implementation/BunitJSObjectReference.cs:line 26
       at Microsoft.JSInterop.JSObjectReferenceExtensions.InvokeVoidAsync(IJSObjectReference jsObjectReference, String identifier, Object[] args)
       at Blazorise.Modules.BaseJSModule.InvokeSafeVoidAsync(String identifier, Object[] args)
       at Blazorise.TextEdit.OnFirstAfterRenderAsync()
       at Blazorise.BaseAfterRenderComponent.OnAfterRenderAsync(Boolean firstRender)
       at Blazorise.BaseComponent.OnAfterRenderAsync(Boolean firstRender)
       at Bunit.Rendering.TestRenderer.AssertNoUnhandledExceptions() in /_/src/bunit.core/Rendering/TestRenderer.cs:line 625
       at Bunit.Rendering.TestRenderer.Render[TResult](RenderFragment renderFragment, Func`2 activator) in /_/src/bunit.core/Rendering/TestRenderer.cs:line 480
       at Bunit.Rendering.TestRenderer.RenderFragment(RenderFragment renderFragment) in /_/src/bunit.core/Rendering/TestRenderer.cs:line 101
       at Bunit.Extensions.TestContextBaseRenderExtensions.RenderInsideRenderTree(TestContextBase testContext, RenderFragment renderFragment) in /_/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs:line 43
       at Bunit.Extensions.TestContextBaseRenderExtensions.RenderInsideRenderTree[TComponent](TestContextBase testContext, RenderFragment renderFragment) in /_/src/bunit.core/Extensions/TestContextBaseRenderExtensions.cs:line 23
       at Bunit.TestContext.Render[TComponent](RenderFragment renderFragment) in /_/src/bunit.web/TestContext.cs:line 68
       at Bunit.TestContext.RenderComponent[TComponent](Action`1 parameterBuilder) in /_/src/bunit.web/TestContext.cs:line 54
       at BookStore.Blazor.Tests.Index_Tests.Index_Test() in C:\Users\dpichowsky\source\abp\abp-samples\BlazorPageUniTest\test\BookStore.Blazor.Tests\Index_Tests.cs:line 25
       at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
       at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
    

    I fear that this error is thrown because he cannot resolve a dynamically created javascript file. This, of course would make testing difficult while working with Blazorize. Do you have an idea on how to work around this or is this a bUnit issue?

    Edit: I pushed the new changes into the repo

  • User Avatar
    0
    PDarioJer created

    Actually, I found this post while looking for a solution: https://github.com/bUnit-dev/bUnit/discussions/305 Removing the SetupModule from the Testbase and replacing it with

    testContext.JSInterop.Mode = JSRuntimeMode.Loose;

    did the trick. I can work with this for now. Though, if you have any concerns with this approach, I would be open to hear them. I gotta admit that I don't fully understand what is going on here.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    In fact, I'm not particularly familiar with bUnit. : )

    I also google the problem.

  • User Avatar
    0
    PDarioJer created

    Fair enough :) In any case, the original problem is solved. Thanks for the help!

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    : )

Made with ❤️ on ABP v9.0.0-preview. Updated on October 07, 2024, 08:52