在 Azure DevOps 以及 .net Core 和 EF Core 中,我使用了不同的技术。
我使用内存数据库中的 SQLite 来执行集成和端到端测试。
目前在 .net Core 中,您可以使用 InMemory 数据库和带有内存选项的 SQLite,在默认的 Azure DevOps CI 代理中运行任何集成测试。
内存中:https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/in-memory
请注意,InMemory 数据库不是关系数据库,它是一种多用途数据库,仅提及一个限制:
InMemory 将允许您保存违反引用的数据
关系数据库中的完整性约束
SQLite 处于内存模式 https://docs.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite
这种方法提供了一个更现实的测试平台。
现在,我走得更远了,我不仅希望能够在 Azure DevOps 中运行具有数据库依赖关系的集成测试,还希望能够在 CI 代理中托管我的 WebAPI,并共享API DBcontext 和我的 Persister 对象之间的数据库(Persister 对象是一个帮助类,它允许我自动生成任何类型的实体并将它们保存到数据库中)。
关于集成测试和 Ent to End 测试的简要说明:
集成测试
涉及数据库的集成测试示例可以是数据访问层的测试。在这种情况下,通常会在开始测试时创建一个 DBContext,用一些数据填充目标数据库,使用被测组件来操作数据,然后再次使用 DBContext 来确保满足断言。
这个场景非常简单,在相同的代码中,您可以共享相同的 DBContext 来生成数据并将其注入到组件中。
端到端测试
想象一下,在我的例子中,您想要测试一个 RESTful .net Core WebAPI,确保您的所有 CRUD 操作都按预期工作,并且您想要测试过滤、分页等是否正确。
在这种情况下,在测试(数据设置和/或验证)和 WebAPI 堆栈之间共享相同的 DBContext 要复杂得多。
.net EF Core 和 WebHostBuilder 之前
到目前为止,我知道唯一可行的方法是拥有一个专用服务器、VM 或 docker 映像,负责提供 API,而这些 API 也必须可以从 Web 或 Azure DevOps 访问。
设置我的集成测试以重新创建数据库,或者足够聪明/有限以完全忽略现有数据,并确保每个测试对数据损坏具有弹性并且完全可靠(没有假阴性或阳性结果)。
然后我必须配置我的构建定义来运行测试。
利用内存中的 SQLite 与 cache=shared 和 WebHostBuilder
下面我首先描述我使用的两种主要技术,然后我添加一些代码来展示如何做到这一点。
SQLite 文件::内存:?cache=shared
SQLite 允许您在内存中工作,而不是使用传统的文件,这已经给我们带来了巨大的性能提升,消除了 I/O 瓶颈,但最重要的是,使用选项 cache=shared,我们可以使用同一进程内的多个连接访问相同的数据。如果您需要多个数据库,您可以指定一个名称。
更多信息: https://www.sqlite.org/inmemorydb.html
WebHostBuilder
.net Core 提供主机构建器,WebHostBuilder 允许我们创建一个服务器来启动和托管我们的 WebAPI,这样就可以像托管在真实服务器上一样访问它。
当您在测试类中使用 WebHostBuilder 时,这两个都生活在同一个进程中。
更多信息: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.webhostbuilder?view=aspnetcore-2.2
解决方案
在初始化 E2E 测试时,创建一个新客户端来连接 api,创建一个 dbcontext,您将使用它来播种数据库并可能进行断言。
测试初始化:
[TestClass]
public class CategoryControllerTests
{
private TestServerApiClient _client;
private Persister<Category> _categoryPersister;
private Builder<Category> _categoryBuilder;
private IHouseKeeperContext _context;
protected IDbContextTransaction Transaction;
[TestInitialize]
public void TestInitialize()
{
_context = ContextProvider.GetContext();
_client = new TestServerApiClient();
ContextProvider.ResetDatabase();
_categoryPersister = new Persister<Category>(_context);
_categoryBuilder = new Builder<Category>();
}
[TestCleanup]
public void Cleanup()
{
_client?.Dispose();
_context?.Dispose();
_categoryPersister?.Dispose();
ContextProvider.Dispose();
}
[...]
}
TestServerApiClient 类:
public class TestServerApiClient : System.IDisposable
{
private readonly HttpClient _client;
private readonly TestServer _server;
public TestServerApiClient()
{
var webHostBuilder = new WebHostBuilder();
webHostBuilder.UseEnvironment("Test");
webHostBuilder.UseStartup<Startup>();
_server = new TestServer(webHostBuilder);
_client = _server.CreateClient();
}
public void Dispose()
{
_server?.Dispose();
_client?.Dispose();
}
}
ContextProvider 类用于生成 DBContext,可用于播种数据或执行数据库查询以获取断言。
public static class ContextProvider
{
private static bool _requiresDbDeletion;
private static IConfiguration _applicationConfiguration;
public static IConfiguration ApplicationConfiguration
{
get
{
if (_applicationConfiguration != null) return _applicationConfiguration;
_applicationConfiguration = new ConfigurationBuilder()
.AddJsonFile("Config/appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
return _applicationConfiguration;
}
}
private static ServiceProvider _serviceProvider;
public static ServiceProvider ServiceProvider
{
get
{
if (_serviceProvider != null) return _serviceProvider;
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<IConfiguration>(ApplicationConfiguration);
var databaseType = ApplicationConfiguration?.GetValue<DatabaseType>("DatabaseType") ?? DatabaseType.SQLServer;
_requiresDbDeletion = databaseType == DatabaseType.SQLServer;
IocConfig.RegisterContext(serviceCollection, null);
_serviceProvider = serviceCollection.BuildServiceProvider();
return _serviceProvider;
}
set
{
_serviceProvider = value;
}
}
/// <summary>
/// Generate the db context
/// </summary>
/// <returns>DB Context</returns>
public static IHouseKeeperContext GetContext()
{
return ServiceProvider.GetService<IHouseKeeperContext>();
}
public static void Dispose()
{
ServiceProvider?.Dispose();
ServiceProvider = null;
}
public static void ResetDatabase()
{
if (_requiresDbDeletion)
{
GetContext()?.Database?.EnsureDeleted();
GetContext()?.Database?.EnsureCreated();
}
}
}
IocConfig 类 是我在框架中用来设置依赖注入的辅助类。上面使用的方法 RegisterContext 负责注册 DBContext 并根据需要进行设置,并且因为这与 WebAPI 使用的类相同,所以使用配置 DatabaseType 来确定要做什么。
在这个类中,你可能会发现大部分的“复杂性”。
在内存中使用 SQLite 时,您必须记住:
- 连接不会像使用 SQL Server 时那样自动打开和关闭(这就是我使用的原因:
context.Database.OpenConnection();)
- 如果没有连接处于活动状态,则删除数据库(这就是我使用
services.AddSingleton<IHouseKeeperContext>(s ... 的原因,重要的是保持一个连接打开,这样数据库不会被破坏,但另一方面你必须小心关闭测试结束时的所有连接,以便数据库最终被销毁,并且下一个测试将正确地创建一个新的空数据库。
课程的其余部分处理生产和测试设置的 SQL Server 配置。我可以随时设置测试以使用 SQL Server 的真实实例,所有测试都将保持完全独立于其他测试,但它肯定会很慢,并且可能仅适用于夜间构建(如果需要,它取决于系统的大小)。
public class IocConfig
{
public static void RegisterContext(IServiceCollection services, IHostingEnvironment hostingEnvironment)
{
var serviceProvider = services.BuildServiceProvider();
var configuration = serviceProvider.GetService<IConfiguration>();
var connectionString = configuration.GetConnectionString(Constants.ConfigConnectionStringName);
var databaseType = DatabaseType.SQLServer;
try
{
databaseType = configuration?.GetValue<DatabaseType>("DatabaseType") ?? DatabaseType.SQLServer;
}catch
{
MyLoggerFactory.CreateLogger<IocConfig>()?.LogWarning("Missing or invalid configuration: DatabaseType");
databaseType = DatabaseType.SQLServer;
}
if(hostingEnvironment != null && hostingEnvironment.IsProduction())
{
if(databaseType == DatabaseType.SQLiteInMemory)
{
throw new ConfigurationErrorsException($"Cannot use database type {databaseType} for production environment");
}
}
switch (databaseType)
{
case DatabaseType.SQLiteInMemory:
// Use SQLite in memory database for testing
services.AddDbContext<HouseKeeperContext>(options =>
{
options.UseSqlite($"DataSource='file::memory:?cache=shared'");
});
// Use singleton context when using SQLite in memory if the connection is closed the database is going to be destroyed
// so must use a singleton context, open the connection and manually close it when disposing the context
services.AddSingleton<IHouseKeeperContext>(s => {
var context = s.GetService<HouseKeeperContext>();
context.Database.OpenConnection();
context.Database.EnsureCreated();
return context;
});
break;
case DatabaseType.SQLServer:
default:
// Use SQL Server testing configuration
if (hostingEnvironment == null || hostingEnvironment.IsTesting())
{
services.AddDbContext<HouseKeeperContext>(options =>
{
options.UseSqlServer(connectionString);
});
services.AddSingleton<IHouseKeeperContext>(s => {
var context = s.GetService<HouseKeeperContext>();
context.Database.EnsureCreated();
return context;
});
break;
}
// Use SQL Server production configuration
services.AddDbContextPool<HouseKeeperContext>(options =>
{
// Production setup using SQL Server
options.UseSqlServer(connectionString);
options.UseLoggerFactory(MyLoggerFactory);
}, poolSize: 5);
services.AddTransient<IHouseKeeperContext>(service =>
services.BuildServiceProvider()
.GetService<HouseKeeperContext>());
break;
}
}
[...]
}
Sample Test,首先我使用持久化器生成的数据播种在数据库中,然后我使用 API 获取数据,测试也可以反转,使用 POST 请求设置数据,然后使用 DBContext 读取 db 并确保创建成功。
[TestMethod]
public async Task GET_support_orderBy_Id()
{
_categoryPersister.Persist(3, (c, i) =>
{
c.Active = 1 % 2 == 0;
c.Name = $"Name_{i}";
c.Description = $"Desc_i";
});
var response = await _client.GetAsync("/api/category?&orderby=Id");
var categories = response.To<List<Category>>();
Assert.That.All(categories).HaveCount(3);
Assert.IsTrue(categories[0].Id < categories[1].Id &&
categories[1].Id < categories[2].Id);
response = await _client.GetAsync("/api/category?$orderby=Id desc");
categories = response.To<List<Category>>();
Assert.That.All(categories).HaveCount(3);
Assert.IsTrue(categories[0].Id > categories[1].Id &&
categories[1].Id > categories[2].Id);
}
结论
我喜欢我可以在 Azure DevOps 中免费运行 E2E 测试这一事实,性能非常好,这给了我很大的信心,非常适合您想要设置持续交付环境时。
这是 Azure DevOps(免费版)中此代码的部分构建执行的屏幕截图。
很抱歉,这比预期的要长。