C#C
C#2y ago
SWEETPONY

✅ A problem with tracking behavior in unit tests

I have this error in unit tests:
The instance of entity type 'QualificationEntity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.


Unit tests look like this:
[Test]
public Task AddAsync_AddWorkingTask_Success() =>
   ExecuteTestCaseWithTestingContextAsync(async context => {
       context.DbContext.Qualifications.Add(qualification);
       context.DbContext.SaveChanges();
        
       ...
    
       await context.WorkingTaskRepository.ScheduleWorkingTaskAsync(workingTask, eventContext);
});

   protected async Task ExecuteTestCaseWithTestingContextAsync(Func<TestingContext, Task> asserter)
    {
        if(asserter == null)
            Assert.Fail();
        var options = CreateDbOptions();
        using(var dbContext = new DbContext(options))
        {
            await dbContext.Database.EnsureDeletedAsync().ConfigureAwait(false);
            await dbContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
            var testingContext = new TestingContext(dbContext);
            await asserter.Invoke(testingContext).ConfigureAwait(false);
        }
    }


everything will be ok if I remove context.DbContext.Qualifications.Add(qualification); but I don't want to
Was this page helpful?