(精華)2020年8月22日 ABP vNext 領域層和資料訪問層的單元測試

愚公搬程式碼發表於2020-08-22

前面我們寫了針對Application的單元測試,現在希望增加對領域層和資料訪問層的單元測試。首先,需要把測試模組的公共程式碼抽提出來,建立一個基礎模組,還要把測試類中的公共程式碼抽提出來,建立一個基礎的測試類。我們在測試目錄下,增加一個新的測試專案,名稱為ZL.ApbNext.Poem.TestBase,在這個測試專案下,增加兩個基礎類:

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Modularity;
using Volo.Abp.Testing;
using Volo.Abp.Uow;

namespace ZL.ApbNext.Poem.TestBase
{
    public abstract class PoemTestBase<TStartupModule> : AbpIntegratedTest<TStartupModule>
        where TStartupModule : IAbpModule
    {
        protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options)
        {
            options.UseAutofac();
        }

        protected virtual Task WithUnitOfWorkAsync(Func<Task> func)
        {
            return WithUnitOfWorkAsync(new AbpUnitOfWorkOptions(), func);
        }

        protected virtual async Task WithUnitOfWorkAsync(AbpUnitOfWorkOptions options, Func<Task> action)
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

                using (var uow = uowManager.Begin(options))
                {
                    await action();

                    await uow.CompleteAsync();
                }
            }
        }

        protected virtual Task<TResult> WithUnitOfWorkAsync<TResult>(Func<Task<TResult>> func)
        {
            return WithUnitOfWorkAsync(new AbpUnitOfWorkOptions(), func);
        }

        protected virtual async Task<TResult> WithUnitOfWorkAsync<TResult>(AbpUnitOfWorkOptions options, Func<Task<TResult>> func)
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var uowManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

                using (var uow = uowManager.Begin(options))
                {
                    var result = await func();
                    await uow.CompleteAsync();
                    return result;
                }
            }
        }

    }
}

模組的基礎類:

using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
using Volo.Abp.Autofac;
using Volo.Abp.Data;
using Volo.Abp.Modularity;
using Volo.Abp.Threading;

namespace ZL.ApbNext.Poem.TestBase
{
    [DependsOn(
        typeof(AbpAutofacModule),
        typeof(AbpTestBaseModule)
        )]
    public class PoemTestBaseModule : AbpModule
    {
        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            SeedTestData(context);
        }

        private static void SeedTestData(ApplicationInitializationContext context)
        {
            AsyncHelper.RunSync(async () =>
            {
                using (var scope = context.ServiceProvider.CreateScope())
                {
                    await scope.ServiceProvider
                        .GetRequiredService<IDataSeeder>()
                        .SeedAsync();
                }
            });
        }
    }
}

然後,我們建立資料訪問層的測試ZL.AbpNext.Poem.EF.Test,這個測試需要使用sqlite作為資料庫,因此在模組中需要進行配置:

using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Sqlite;
using Volo.Abp.Modularity;
using ZL.AbpNext.Poem.EF.EntityFramework;
using ZL.ApbNext.Poem.TestBase;

namespace ZL.AbpNext.Poem.EF.Test
{
    [DependsOn(
        typeof(PoemDataModule),
        typeof(PoemTestBaseModule),
        typeof(AbpEntityFrameworkCoreSqliteModule)
        )]
    public class PoemEFTestModule:AbpModule
    {
        private SqliteConnection _sqliteConnection;
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            ConfigureInMemorySqlite(context.Services);
        }
        private void ConfigureInMemorySqlite(IServiceCollection services)
        {
            _sqliteConnection = CreateDatabaseAndGetConnection();

            services.Configure<AbpDbContextOptions>(options =>
            {
                options.Configure(context =>
                {
                    context.DbContextOptions.UseSqlite(_sqliteConnection);
                });
            });
        }
        public override void OnApplicationShutdown(ApplicationShutdownContext context)
        {
            _sqliteConnection.Dispose();
        }

        private static SqliteConnection CreateDatabaseAndGetConnection()
        {
            var connection = new SqliteConnection("Data Source=:memory:");
            connection.Open();

            var options = new DbContextOptionsBuilder<PoemDbContext>()
                .UseSqlite(connection)
                .Options;

            using (var context = new PoemDbContext(options))
            {
                context.GetService<IRelationalDatabaseCreator>().CreateTables();
            }

            return connection;
        }
    }
}

測試類從測試基類派生:

using System;
using System.Collections.Generic;
using System.Text;
using ZL.ApbNext.Poem.TestBase;

namespace ZL.AbpNext.Poem.EF.Test
{
    public abstract class PoemEFTestBase:PoemTestBase<PoemEFTestModule>
    {
    }
}

在此基礎上,可以建立具體的測試,示例如下:

using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Xunit;
using ZL.AbpNext.Poem.Core.Poems;

namespace ZL.AbpNext.Poem.EF.Test
{
    public class TestRepository: PoemEFTestBase
    {
        IRepository<Category> categoryRepository;
        public TestRepository()
        {
            categoryRepository = GetRequiredService<IRepository<Category>>();
        }
        [Fact]
        public async Task TestAddCategory()
        {
            await WithUnitOfWorkAsync(async () =>
            {
               var cate= categoryRepository.InsertAsync(new Category { CategoryName = "測試" },true);
                Assert.True(cate.Id > 0);
            });
        }
    }
}

使用同樣的方法,建立針對領域層的測試ZL.AbpNext.Poem.Core.Test並改造現有的ZL.AbpNext.Poem.Application.Test。

相關文章