ABP框架使用(版本3.3.1) - Test Project

1.  foreign key constraint failed

在TestDataBuilder 中已经加了IdentityUser,但测试Application的时候,还是会报错

TestDataBuilder 

        private async Task AddUsers()
        {
            var adminUser = new IdentityUser(_guidGenerator.Create(), "administrator", "admin@abp.io");
            adminUser.AddRole(_adminRole.Id);
            adminUser.AddClaim(_guidGenerator, new Claim("TestClaimType", "42"));
            await _userRepository.InsertAsync(adminUser);

        }
1
2
3
4
5
6
7
protected override void AfterAddApplication(IServiceCollection services)
{
    _currentUser = Substitute.For<ICurrentUser>();
    _currentUser.Id.Returns(_testData.UserJohnId);
    _currentUser.IsAuthenticated.Returns(true);
    services.AddSingleton(_currentUser);
}

这种方法不起作用
optionsBuilder.UseSqlite($"Filename={databaseName}", x => x.SuppressForeignKeyEnforcement());

可以在连接字符串里指定不用Foreign Keys参数
AbpIdentityEntityFrameworkCoreTestModule

1
var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=False");

2. 测试的application方法disable了UOW,会报错Context已经displose

                await WithUnitOfWorkAsync(async () =>
            {
...

            });

3.Substitue 其它

ISettingProvider _settingProvider = Substitute.For<ISettingProvider>();
            _settingProvider.GetOrNullAsync(Arg.Any<string>()).Returns((string) null);
_settingProvider.GetOrNullAsync(IdentitySettingNames.Password.RequiredLength).Returns(Task.FromResult("42"));
            services.Replace(ServiceDescriptor.Singleton(_settingProvider));

Substitue DomainService

复制代码
    public class ItemManager : DomainService
    {
        public ItemManager()
        {

        }
        public virtual  string GetTestData()
        {
            return "GetTestData";

        }

    }
复制代码

Test

复制代码
        protected override void AfterAddApplication(IServiceCollection services)
        {
            _itemManager = Substitute.For<ItemManager>();
            _itemManager.GetTestData().Returns("MockData");
            services.AddTransient(provider => _itemManager);
        }

        [Fact]
        public  void Should_Get_Mock_Data()
        {
            var result = _itemManager.GetTestData();
            result.ShouldBe("MockData");
        }
复制代码

 但如果DomainService有注入其它参数,就会报错

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class:Items.ItemManager.
Could not find a parameterless constructor.

复制代码
    public class ItemManager : DomainService
    {
        private IRepository<Item, Guid> _repository;
        public ItemManager(IRepository<Item, Guid> repository)
        {
            _repository = repository;
        }
        public virtual  string GetTestData()
        {
            return "GetTestData";

        }

    }
复制代码

GetRequiredService 获取参数会报错
System.ArgumentNullException : Value cannot be null. (Parameter 'provider')

必须将所需的参数Substitue出来传递进去

复制代码
        protected override void AfterAddApplication(IServiceCollection services)
        {
            // var repository = ServiceProvider.GetRequiredService<IRepository<Item, Guid>>();
            var repository = Substitute.For<IRepository<Item, Guid>>();
            services.AddSingleton(repository);
            _itemManager = Substitute.For<ItemManager>(repository);
            _itemManager.GetTestData().Returns("MockData");
            services.AddTransient(provider => _itemManager);
        }
复制代码

 

 4.判断报某种Exception

            var exception = await Assert.ThrowsAsync<UserFriendlyException>(
                async () => await _testAppService.UpdateAsync(beforeEntity.Id, testDto)
            );
            exception.Code.Contains("Unique").Should().BeTrue();

 5.NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException: Could not find a call to return from.

Make sure you called Returns() after calling your substitute (for example: mySub.SomeMethod().Returns(value)), and that you are not configuring other substitutes within Returns() (for example, avoid this: mySub.SomeMethod().Returns(ConfigOtherSub())).

If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member. Return values cannot be configured for non-virtual/non-abstract members.

posted on   白马酒凉  阅读(140)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示