当每个测试单独运行时,xunit抛出AggregateException(用户无权更改数据库)



我试图对存储库模式与数据库进行一些集成测试,我面临的问题是,每个测试单独运行都很好,但当它试图运行所有测试xUnit时,会抛出以下错误

消息:System.AggregateException:出现一个或多个错误。(用户无权更改数据库"PharoesTechDBTest",该数据库不存在,或者该数据库未处于允许访问检查的状态。ALTER DATABASE语句失败。((以下构造函数参数没有匹配的fixture数据:DatabaseFixture fixture(----Microsoft.Data.SqlClient.SqlException:用户无权更改数据库"PharoesTechDBTest",该数据库不存在,或者该数据库未处于允许访问检查的状态。ALTER DATABASE语句失败。----以下构造函数参数没有匹配的fixture数据:DatabaseFixture fixture

DatabaseFixture

public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
var factory = new ApplicationContextFactory();
Context = factory.CreateDbContext(Array.Empty<string>());
// drop and recreate new database
Context.Database.EnsureDeleted();
Context.Database.EnsureCreated();
}
public void Dispose()
{
Context.Dispose();
}
public ApplicationDbContext Context { get; }
}

第一个测试类

public class CategorysRepoTests : IClassFixture<DatabaseFixture>, IClassFixture<LoggerFixture>
{
private readonly ICategoryRepo _repo;
private readonly DatabaseFixture _dbfixture;
public CategorysRepoTests(DatabaseFixture fixture, LoggerFixture loggerFixture)
{
_dbfixture = fixture;
_repo = new CategoriesRepo(fixture.Context, loggerFixture.Logger);
}
[Fact]
[Trait("Category", "IntegrationTest")]
public async Task CreateCategorySuccessfully()
{
Assert.Empty(_dbfixture.Context.Categories);
var newCategory = DataGenerator.CreateCategory();
// insert category
await _repo.AddAsycn(newCategory);
_dbfixture.Context.ChangeTracker.Clear();
// Check if ID was set
Assert.True(newCategory.Id > 0);
// Make sure that Category is in DB
var categories = await _dbfixture.Context.Categories.Where(u => u.Id == newCategory.Id).ToListAsync();
Assert.NotEmpty(categories);
}
}

第二测试类

public class MediaTypeRepoTests : IClassFixture<DatabaseFixture>,IClassFixture<LoggerFixture>
{
private readonly DatabaseFixture _dbfixture;
private readonly IMediaTypeRepo _repo;
public MediaTypeRepoTests(DatabaseFixture fixture,LoggerFixture logger)
{
_dbfixture = fixture;
_repo = new MediaTypesRepo(_dbfixture.Context, logger.Logger);
}
[Fact]
[Trait("Category", "IntegrationTest")]
public async Task MediaTypeRepoContainsDatatOnNewlyCreatedDb()
{

var medias = await _repo.GetAllAsync();
Assert.NotEmpty(medias);
}
}

数据生成器

public class DataGenerator
{
public static Category CreateCategory()
{
return new Category
{
Title = "test title",
ThumbnailImagePath = "some thubnail",
};
}
}

为什么他们每个人都单独跑,但当我试图一起跑时,却会出错??!缺陷在哪里?

正如@Christopher所提到的,这是一个并行性问题,我通过在整个项目级上禁用并行性来解决它

global using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]

阅读更多关于并行测试的信息

最新更新