【发布时间】:2021-08-12 03:25:16
【问题描述】:
我正在为我的 Web API 编写一些集成测试,这意味着它必须在测试执行期间运行。有什么方法可以使用内存数据库而不是基于 SQL Server 的真实数据库来运行它?
另外,我需要一次运行几个实例,所以我需要以某种方式将每个实例的基地址更改为唯一的。例如,我可以将以下代码中提到的这些实例 ID 附加到基本 URL。
这是我用来为我的测试运行一个新实例的代码:
public static class WebApiHelper
{
private const string ExecutableFileExtension = "exe";
private static readonly Dictionary<Guid, Process> _instances = new();
public static void EnsureIsRunning(Assembly? assembly, Guid instanceId)
{
if (assembly is null)
throw new ArgumentNullException(nameof(assembly));
var executableFullName = Path.ChangeExtension(
assembly.Location, ExecutableFileExtension);
_instances.Add(instanceId, Process.Start(executableFullName));
}
public static void EnsureIsNotRunning(Guid instaceId)
=> _instances[instaceId].Kill();
}
总的来说,这是创建测试实例的好方法,还是我遗漏了什么?问这个,因为也许有另一种“合法”的方式来实现我的目标。
【问题讨论】:
-
in-memory database是什么意思,我可以知道你的意思吗? -
@MdFaridUddinKiron,我的意思是 DbContext 配置为使用方法
UseInMemoryDatabase();。我知道如何使用它,但我需要以某种方式确定我的 API 实例是通过测试运行还是只是正常启动。 -
是的,我希望您也可以在您的 startup.cs 文件中确定这一点。
-
您应该小心使用 InMemoryDatabase。不支持关系、存储过程等SQL特性,也可以使用SQLite。
-
@İbrahimULUDAĞ,谢谢!我不知道。然后我将创建一个临时数据库并在测试完成后将其删除。
标签: c# integration-testing asp.net-core-webapi