gpt4 book ai didi

c# - 在 AutoFixture 自定义上调用 Dispose 方法

转载 作者:太空狗 更新时间:2023-10-29 20:24:32 32 4
gpt4 key购买 nike

我正在使用 AutoFixture 定制来测试访问 SQL Compact 数据库的存储库。

一旦测试完成就删除这个数据库对我很有帮助。因为数据库是在自定义构造函数中创建的,所以我认为删除它的最佳位置是在 dispose 方法中。

我想的代码是:

internal class ProjectRepositoryCustomization : ICustomization
{
private readonly String _dbLocation;

public ProjectRepositoryCustomization()
{
var tempDbLocation = Path.Combine(Path.GetTempPath(), "TempDbToDelete");
if (!Directory.Exists(tempDbLocation))
{
Directory.CreateDirectory(tempDbLocation);
}

_dbLocation = Path.Combine(tempDbLocation, Guid.NewGuid().ToString("N") + ".sdf");
}

public void Customize(IFixture fixture)
{
DataContextConfiguration.database = _dbLocation;

var dataContextFactory = new BaseDataContextFactory();
var projRepository = new ProjectRepository(dataContextFactory);
fixture.Register(() => projRepository);
}

public void Dispose()
{
if (File.Exists(_dbLocation))
{
File.Delete(_dbLocation);
}
}
}

是否可以做类似的事情?

最佳答案

正如@Ruben Bartelink 在评论中指出的那样,可能。但是,我会推荐一种不同的方法,原因如下。

管理对象的生命周期是您通常希望能够使用 IoC 容器完成的事情。然而,AutoFixture 尽管它可能看起来 是一个 IoC 容器,但它实际上是 not meant to be one :

AutoFixture shares a lot of similarities with DI Containers. It supports auto-wiring and it can be configured to create instances in lots of interesting ways. However, since the focus is different, it does some things better and some things not as well as a DI Container.

AutoFixture 的主要目标是使创建 anonymous test data 变得容易在一些可配置的范围内。它的 API 侧重于允许程序员自定义生成测试数据的方式,而不是多长时间,因为假定它仅被消耗 within the context of a test :

AutoFixture is weaker when it comes to lifetime management. A Fixture is never expected to exist for more than a single test case, so it makes no sense to model any other lifestyle than Transient and Singleton. [...] It doesn't have to, because it's not a DI Container.

另一方面,测试框架非常擅长管理测试装置的生命周期。由于您所描述的通常是管理集成测试的上下文的一部分,因此我会在之前之后运行它fixture 被执行。

例如:

[TestFixture]
public class WithDatabaseContext
{
private string dbLocation;
private BaseDataContextFactory dataContextFactory

protected BaseDataContextFactory DataContextFactory
{
get { return this.dataContextFactory; }
}

[TestFixtureSetUp]
public void FixtureInit()
{
// Initialize dbLocation
// Initialize dataContextFactory
}

[TestFixtureTearDown]
public void FixtureDispose()
{
// Delete file at dbLocation
}
}

然后您的测试可以继承上下文并使用它来配置 AutoFixture:

[TestFixture]
public void SomeTest : WithDatabaseContext
{
private IFixture fixture;

[SetUp]
public void Init()
{
this.fixture = new Fixture();
this.fixture.Register(
() => new ProjectRepository(base.DataContextFactory));
}

[Test]
public void Doing_something_should_return_something_else()
{
// ...
}
}

在这种情况下,利用测试框架来管理临时数据库的生命周期在测试上下文中清楚地传达了它的边界。在我看来,将它隐藏在 AutoFixture 定制中会使其不那么明显,而且可以说更难使用。

关于c# - 在 AutoFixture 自定义上调用 Dispose 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15496493/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com