【发布时间】:2015-12-17 07:10:01
【问题描述】:
我是集成测试的新手,我正在寻找有关我的问题解决方法的一些解释和建议:
我在测试中使用 TransactionScope 来保持数据库清洁,并在每次测试之前创建新的 TransactionScope 并在每次测试后处理它:
[SetUp]
public void Init()
{
this.scope = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted },
TransactionScopeAsyncFlowOption.Enabled);
this.context = new SportsPerformanceDbContext();
this.questRepo = new QuestionRepository(this.context);
}
[TearDown]
public void CleanAll()
{
this.context.Dispose();
this.scope.Dispose();
}
当我运行一个测试类时,一切正常。但是当我运行至少两个测试类时,我遇到了一个问题:在这个测试中(见下文)lasrQuestionId 等于数据库中的最后一个问题 id - 没关系,但是 actualResultId em> 等于 Id_of_the_last_added_question_in_tests_with_transaction_scope + 1:
[Test]
public async void AddAsyncTest()
{
// Arrange
var questionModel = new QuestionModel
{
//some properties
};
Question lastQuestion = this.GetLastQuestion();
var lastQuestionId = lastQuestion?.Id ?? 0;
// Act
var addResult = await this.questRepo.AddAsync(questionModel);
var actualResult = addResult.Value;
// Assert
Assert.AreEqual(lastQuestionId + 1, actualResult.Id);
// some other assertions
}
所以我有以下内容,例如,lastQuestionId 是 5(数据库中有 5 个问题),但 actualResult Id 是 16(因为我之前在其他测试)... 我认为我的 context 或 scope.dispose() 有问题。我不知道哪里出了问题,你能解释一下我在这里做错了什么吗?提前致谢!
this.GetLastQuestion() 代码如下:
private Question GetLastQuestion()
{
using (var ctx = new SportsPerformanceDbContext())
{
return ctx.Question
.OrderByDescending(q => q.Id)
.FirstOrDefault();
}
}
【问题讨论】:
标签: c# entity-framework testing entity-framework-6 transactionscope