内存数据库中的集成测试sqlite在.NET Core中出现错误

问题描述 投票:0回答:1

我在 .NET Core 应用程序中设置集成测试,但在第 53 行(即

appContext.Database.EnsureCreated()
)中出现错误:

$exception {“SQLite 错误 1:'靠近“''”:语法错误'。”}
Microsoft.Data.Sqlite.SqliteException

谁能告诉我出了什么问题吗?

using Asp.Versioning;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Data.Common;
using System.Xml.Linq;
using World.Persistence.DBContext;


namespace World.Integration.Tests
{
    public abstract class CustomWebApplicationFactory<TProgram>
    : WebApplicationFactory<TProgram> where TProgram : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                var dbContextDescriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbContextOptions<WorldDBContext>));

                services.Remove(dbContextDescriptor!);

                var dbConnectionDescriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbConnection));

                _ = services.Remove(dbConnectionDescriptor!);

                // Create open SqliteConnection so EF won't automatically close it.
                services.AddSingleton<DbConnection>(container =>
                {
                    var connection = new SqliteConnection("DataSource=:memory:");
                    connection.Open();

                    return connection;
                });

                services.AddDbContext<WorldDBContext>((container, options) =>
                {
                    var connection = container.GetRequiredService<DbConnection>();
                    options.UseSqlite(connection);
                });

                var sp = services.BuildServiceProvider();

                using var scope = sp.CreateScope();
                using var appContext = scope.ServiceProvider.GetRequiredService<WorldDBContext>();

                try
                {
                    appContext.Database.EnsureCreated();
                }
                catch (Exception)
                {
                    throw;
                }
            });

            builder.UseEnvironment("Development");
        }
    }
}
c# .net asp.net-core integration-testing system.data.sqlite
1个回答
0
投票

我用您的代码重现了您的问题,这是由 DbContexnt 中的

.HasDefaultValueSql()
方法中的 Sql 无效引起的,将其删除,用有效的 Sql 重新替换它,或者仅调用 HasDefaultValue() 将有助于解决您的问题

© www.soinside.com 2019 - 2024. All rights reserved.