Base solution for your next web application
Open Closed

Simple test case failed #7043


User avatar
0
dzungle created

Hi support team,

I just follow the PhoneBookDemo sample to create an application service. Everything run well, except the test. I've tried several times, but cannot pass the test. Please, help me figure it out. The following is the error message.

Test Name: Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter Test FullName: Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter Test Source: C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs : line 23 Test Outcome: Failed Test Duration: 0:00:00.001

Result StackTrace: at Ips.Migrations.Seed.Host.DefaultSettingsCreator.Create() in C:\Git\Ips\aspnet-core\src\Ips.EntityFrameworkCore\Migrations\Seed\Host\DefaultSettingsCreator.cs:line 27 at Ips.Migrations.Seed.Host.InitialHostDbBuilder.Create() in C:\Git\Ips\aspnet-core\src\Ips.EntityFrameworkCore\Migrations\Seed\Host\InitialHostDbBuilder.cs:line 19 at Ips.Migrations.Seed.SeedHelper.SeedHostDb(IpsDbContext context) in C:\Git\Ips\aspnet-core\src\Ips.EntityFrameworkCore\Migrations\Seed\SeedHelper.cs:line 26 at Ips.Migrations.Seed.SeedHelper.WithDbContext[TDbContext](IIocResolver iocResolver, Action1 contextAction) in C:\Git\Ips\aspnet-core\src\Ips.EntityFrameworkCore\Migrations\Seed\SeedHelper.cs:line 42 at Ips.Migrations.Seed.SeedHelper.SeedHostDb(IIocResolver iocResolver) in C:\Git\Ips\aspnet-core\src\Ips.EntityFrameworkCore\Migrations\Seed\SeedHelper.cs:line 18 at Ips.EntityFrameworkCore.IpsEntityFrameworkCoreModule.PostInitialize() in C:\Git\Ips\aspnet-core\src\Ips.EntityFrameworkCore\EntityFrameworkCore\IpsEntityFrameworkCoreModule.cs:line 61 at System.Collections.Generic.List1.ForEach(Action1 action) at Abp.AbpBootstrapper.Initialize() in D:\Github\aspnetboilerplate\src\Abp\AbpBootstrapper.cs:line 155 at Abp.TestBase.AbpIntegratedTestBase1.InitializeAbp() in D:\Github\aspnetboilerplate\src\Abp.TestBase\TestBase\AbpIntegratedTestBase.cs:line 53 at Ips.Test.Base.AppTestBase`1..ctor() in C:\Git\Ips\aspnet-core\test\Ips.Test.Base\AppTestBase.cs:line 30 at Ips.Tests.AppTestBase..ctor() at Ips.Tests.Common.CategoryAppService_Tests..ctor() in C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs:line 17 Result Message: System.NullReferenceException : Object reference not set to an instance of an object.


15 Answer(s)
  • User Avatar
    0
    aaron created
    Support Team

    Which object reference is null? Show the relevant code.

  • User Avatar
    0
    dzungle created

    Hi @aaron,

    This is my test code:

    public class CategoryAppService_Tests : AppTestBase
        {
            private readonly ICategoryAppService _categoryAppService;
    
            public CategoryAppService_Tests()
            {
                _categoryAppService = Resolve<ICategoryAppService>();
            }
    
            [Fact]
            public async Task Should_Get_All_Categories_Without_Any_Filter()
            {
                //Act
                var categories = await _categoryAppService.GetCategories(new GetCategoriesInput());
    
                //Assert
                categories.Items.Count.ShouldBe(2);
            }
        }
    

    This is my service code:

    public class CategoryAppService : IpsAppServiceBase, ICategoryAppService
        {
            private readonly IRepository<Category> _categoryRepository;
    
            public CategoryAppService(IRepository<Category> categoryRepository)
            {
                _categoryRepository = categoryRepository;
            }
    
            public async Task<ListResultDto<CategoryListDto>> GetCategories(GetCategoriesInput input)
            {
                var categories = await _categoryRepository
                    .GetAll()
                    .WhereIf(
                        !input.Filter.IsNullOrEmpty(),
                        c => c.Title.Contains(input.Filter) ||
                             c.Description.Contains(input.Filter)
                    )
                    .OrderBy(c => c.Title)
                    .ToListAsync();
    
                return new ListResultDto<CategoryListDto>(categories.MapTo<List<CategoryListDto>>());
            }
        }
    
  • User Avatar
    0
    dzungle created

    And this is my entity, dto, mapping and interface code:

    public class Category : FullAuditedEntity
        {
            [Required]
            [MaxLength(CategoryConsts.MaxTitleLength)]
            public virtual string Title { get; set; }
    
            [Required]
            [MaxLength(CategoryConsts.MaxDescriptionLength)]
            public virtual string Description { get; set; }
    
            [MaxLength(CategoryConsts.MaxTypeLength)]
            public virtual string Type { get; set; }
        }
    
    public class CategoryListDto : FullAuditedEntityDto
        {
            public string Title { get; set; }
    
            public string Description { get; set; }
    
            public string Type { get; set; }
        }
    
    public class GetCategoriesInput
        {
            public string Filter { get; set; }
        }
    
    configuration.CreateMap<Category, CategoryListDto>();
    
    public interface ICategoryAppService : IApplicationService
        {
            Task<ListResultDto<CategoryListDto>> GetCategories(GetCategoriesInput input);
        }
    
  • User Avatar
    0
    aaron created
    Support Team

    Which object reference is null?

  • User Avatar
    0
    dzungle created

    I really don't know which object, because I just follow the sample and these above are all my codes. As instructed, I also set the MultiTenancyEnabled = false.

    Looking at the error message, I guess something wrong happens in the DefaultSettingsCreator (come with the aspnet zero). Can you have a look at the error message, please?

    Thank you

  • User Avatar
    0
    aaron created
    Support Team

    Duplicate of #6824


    Thanks for mentioning this:

    I also set the MultiTenancyEnabled = false.

  • User Avatar
    0
    dzungle created

    Hi @aaron,

    I have fixed the issue as instructed:

    if (IpsConsts.MultiTenancyEnabled == false)
                {
                    //var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == MultiTenancy.Tenant.DefaultTenantName);
                    //tenantId = defaultTenant.Id;
                    tenantId = MultiTenancyConsts.DefaultTenantId;
                }
    

    But I still cannot pass the test, here is the error message:

    Test Name: Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter Test FullName: Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter Test Source: C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs : line 23 Test Outcome: Failed Test Duration: 0:01:25.11

    Result StackTrace: at AutoMapper.Mapper.get_Instance() in C:\projects\automapper\src\AutoMapper\Mapper.cs:line 36 at AutoMapper.Mapper.Map[TDestination](Object source) in C:\projects\automapper\src\AutoMapper\Mapper.cs:line 76 at Ips.Common.CategoryAppService.GetCategories(GetCategoriesInput input) in C:\Git\Ips\aspnet-core\src\Ips.Application\Common\CategoryAppService.cs:line 35 at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task1 actualReturnValue, Func1 postAction, Action1 finalAction) at Abp.Threading.InternalAsyncHelper.AwaitTaskWithFinallyAndGetResult[T](Task1 actualReturnValue, Action`2 finalAction) at Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter() in C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs:line 26 --- End of stack trace from previous location where exception was thrown --- Result Message: System.InvalidOperationException : Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

  • User Avatar
    0
    dzungle created

    Hi mate,

    I have configed module dependency, but still get error running test:

    Test Name: Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter Test FullName: Ips.Tests.Common.CategoryAppService_Tests.Should_Get_All_Categories_Without_Any_Filter Test Source: C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs : line 23 Test Outcome: Failed Test Duration: 0:00:00.001

    Result StackTrace: at Castle.MicroKernel.SubSystems.Naming.DefaultNamingSubSystem.Register(IHandler handler) at Castle.MicroKernel.DefaultKernel.AddCustomComponent(ComponentModel model) at Castle.MicroKernel.Registration.ComponentRegistration1.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) at Castle.MicroKernel.DefaultKernel.Register(IRegistration[] registrations) at Castle.Windsor.WindsorContainer.Register(IRegistration[] registrations) at Abp.Dependency.IocManager.Register[TType,TImpl](DependencyLifeStyle lifeStyle) in D:\Github\aspnetboilerplate\src\Abp\Dependency\IocManager.cs:line 140 at Abp.Zero.Configuration.LanguageManagementConfig.EnableDbLocalization() in D:\Github\aspnetboilerplate\src\Abp.Zero.Common\Zero\Configuration\LanguageManagementConfig.cs:line 29 at Ips.Tests.IpsTestModule.PreInitialize() in C:\Git\Ips\aspnet-core\test\Ips.Tests\IpsTestModule.cs:line 43 at System.Collections.Generic.List1.ForEach(Action1 action) at Abp.Modules.AbpModuleManager.StartModules() in D:\Github\aspnetboilerplate\src\Abp\Modules\AbpModuleManager.cs:line 47 at Abp.AbpBootstrapper.Initialize() in D:\Github\aspnetboilerplate\src\Abp\AbpBootstrapper.cs:line 155 at Abp.TestBase.AbpIntegratedTestBase1.InitializeAbp() in D:\Github\aspnetboilerplate\src\Abp.TestBase\TestBase\AbpIntegratedTestBase.cs:line 53 at Ips.Test.Base.AppTestBase`1..ctor() in C:\Git\Ips\aspnet-core\test\Ips.Test.Base\AppTestBase.cs:line 30 at Ips.Tests.AppTestBase..ctor() at Ips.Tests.Common.CategoryAppService_Tests..ctor() in C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs:line 17 Result Message: Castle.MicroKernel.ComponentRegistrationException : Component Abp.Localization.ApplicationLanguageProvider could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.

    I guess the test project of version 6.9.1 is not stable. Could you have a look, please?

  • User Avatar
    0
    dzungle created

    Here is my code:

    namespace Ips.Tests
    {
        [DependsOn(
            typeof(IpsApplicationModule),
            typeof(IpsEntityFrameworkCoreModule),
            typeof(IpsTestBaseModule))]
        public class IpsTestModule : AbpModule
        {
            public IpsTestModule(IpsEntityFrameworkCoreModule abpZeroTemplateEntityFrameworkCoreModule)
            {
                abpZeroTemplateEntityFrameworkCoreModule.SkipDbContextRegistration = true;
            }
    
            public override void PreInitialize()
            {
                Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30);
                Configuration.UnitOfWork.IsTransactional = false;
    
                //Disable static mapper usage since it breaks unit tests (see https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2052)
                Configuration.Modules.AbpAutoMapper().UseStaticMapper = false;
    
                //Use database for language management
                Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();
    
                RegisterFakeService<AbpZeroDbMigrator>();
    
                IocManager.Register<IAppUrlService, FakeAppUrlService>();
                IocManager.Register<IWebUrlService, FakeWebUrlService>();
                IocManager.Register<IRecaptchaValidator, FakeRecaptchaValidator>();
    
                Configuration.ReplaceService<IAppConfigurationAccessor, TestAppConfigurationAccessor>();
                Configuration.ReplaceService<IEmailSender, NullEmailSender>(DependencyLifeStyle.Transient);
            }
    
            public override void Initialize()
            {
                ServiceCollectionRegistrar.Register(IocManager);
            }
    
            private void RegisterFakeService<TService>()
                where TService : class
            {
                IocManager.IocContainer.Register(
                    Component.For<TService>()
                        .UsingFactoryMethod(() => Substitute.For<TService>())
                        .LifestyleSingleton()
                );
            }
        }
    }
    
  • User Avatar
    0
    aaron created
    Support Team

    From Object To Object Mapping - Unit Tests:

    1. Always use IObjectMapper, do not use MapTo extension methods.

    Change:

    - categories.MapTo<List<CategoryListDto>>()
    + ObjectMapper.Map<List<CategoryListDto>>(categories)
    
  • User Avatar
    0
    dzungle created

    Hi @aaron,

    I still get error:

    Result Message: Castle.MicroKernel.ComponentRegistrationException : Component Abp.Localization.ApplicationLanguageProvider could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.

    Result StackTrace: at Castle.MicroKernel.SubSystems.Naming.DefaultNamingSubSystem.Register(IHandler handler) at Castle.MicroKernel.DefaultKernel.AddCustomComponent(ComponentModel model) at Castle.MicroKernel.Registration.ComponentRegistration1.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) at Castle.MicroKernel.DefaultKernel.Register(IRegistration[] registrations) at Castle.Windsor.WindsorContainer.Register(IRegistration[] registrations) at Abp.Dependency.IocManager.Register[TType,TImpl](DependencyLifeStyle lifeStyle) in D:\Github\aspnetboilerplate\src\Abp\Dependency\IocManager.cs:line 140 at Abp.Zero.Configuration.LanguageManagementConfig.EnableDbLocalization() in D:\Github\aspnetboilerplate\src\Abp.Zero.Common\Zero\Configuration\LanguageManagementConfig.cs:line 29 at Ips.Tests.IpsTestModule.PreInitialize() in C:\Git\Ips\aspnet-core\test\Ips.Tests\IpsTestModule.cs:line 43 at System.Collections.Generic.List1.ForEach(Action1 action) at Abp.Modules.AbpModuleManager.StartModules() in D:\Github\aspnetboilerplate\src\Abp\Modules\AbpModuleManager.cs:line 47 at Abp.AbpBootstrapper.Initialize() in D:\Github\aspnetboilerplate\src\Abp\AbpBootstrapper.cs:line 155 at Abp.TestBase.AbpIntegratedTestBase1.InitializeAbp() in D:\Github\aspnetboilerplate\src\Abp.TestBase\TestBase\AbpIntegratedTestBase.cs:line 53 at Ips.Test.Base.AppTestBase`1..ctor() in C:\Git\Ips\aspnet-core\test\Ips.Test.Base\AppTestBase.cs:line 30 at Ips.Tests.AppTestBase..ctor() at Ips.Tests.Common.CategoryAppService_Tests..ctor() in C:\Git\Ips\aspnet-core\test\Ips.Tests\Common\CategoryAppService_Tests.cs:line 17

    Could you please have a check with my TestModule class?

    namespace Ips.Tests
    {
        [DependsOn(
            typeof(IpsApplicationModule),
            typeof(IpsEntityFrameworkCoreModule),
            typeof(IpsTestBaseModule))]
        public class IpsTestModule : AbpModule
        {
            public IpsTestModule(IpsEntityFrameworkCoreModule abpZeroTemplateEntityFrameworkCoreModule)
            {
                abpZeroTemplateEntityFrameworkCoreModule.SkipDbContextRegistration = true;
            }
    
            public override void PreInitialize()
            {
                Configuration.UnitOfWork.Timeout = TimeSpan.FromMinutes(30);
                Configuration.UnitOfWork.IsTransactional = false;
    
                //Disable static mapper usage since it breaks unit tests (see https://github.com/aspnetboilerplate/aspnetboilerplate/issues/2052)
                Configuration.Modules.AbpAutoMapper().UseStaticMapper = false;
    
                //Use database for language management
                Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();
    
                RegisterFakeService&lt;AbpZeroDbMigrator&gt;();
    
                IocManager.Register&lt;IAppUrlService, FakeAppUrlService&gt;();
                IocManager.Register&lt;IWebUrlService, FakeWebUrlService&gt;();
                IocManager.Register&lt;IRecaptchaValidator, FakeRecaptchaValidator&gt;();
    
                Configuration.ReplaceService&lt;IAppConfigurationAccessor, TestAppConfigurationAccessor&gt;();
                Configuration.ReplaceService&lt;IEmailSender, NullEmailSender&gt;(DependencyLifeStyle.Transient);
            }
    
            public override void Initialize()
            {
                ServiceCollectionRegistrar.Register(IocManager);
            }
    
            private void RegisterFakeService&lt;TService&gt;()
                where TService : class
            {
                IocManager.IocContainer.Register(
                    Component.For&lt;TService&gt;()
                        .UsingFactoryMethod(() => Substitute.For&lt;TService&gt;())
                        .LifestyleSingleton()
                );
            }
        }
    }
    
  • User Avatar
    0
    maliming created
    Support Team

    hi @dzungle

    You search to see if it is called at another layer. The default should be called in the web.core layer.

    Configuration.Modules.Zero().LanguageManagement.EnableDbLocalization();

  • User Avatar
    0
    dzungle created

    Hi @maliming

    I found one more call in the TestBaseModule (Test.Base project).

    How can I solve this issue?

  • User Avatar
    0
    maliming created
    Support Team

    Keep one in the test project, you can try remove one of them.

  • User Avatar
    0
    aaron created
    Support Team

    It was removed from *TestModule.cs in v6.8.0.