单元测试时C#DbContext跟踪失败

问题描述

所以我有一个存储库类,我正在尝试为其编写一些简单的单元测试。但是,当运行删除单元测试时,我一直收到此错误

UserDefaults

我的单元测试代码

The instance of entity type 'Item' cannot be tracked because another instance with the key value
'{Id: 1}' is already being tracked. When attaching existing entities,ensure that only one entity
instance with a given key value is attached.

我的存储库代码

       [SetUp]
        public void Setup()
        {
            _context = new MyDbContext(
                new DbContextOptionsBuilder<MyDbContext>()
                    .UseInMemoryDatabase(Guid.NewGuid().ToString())
                    .EnableSensitiveDataLogging()
                    .Options
            );

            _repository = new Repository(_context);

            var item = new Item
                {
                    Id = 1,Value = "Example"
                };

            _context.Items.Add(item);
            _context.SaveChanges();
        }

        [TearDown]
        public void TearDown()
        {
            _context.dispose();
        }

        [Test]
        public async Task TestdismissportfolioHighlight()
        {
            var sample = new Item { Id = 1 };

            // Without this line here I get the listed error
            _context.ChangeTracker.Entries().ForEach(e => e.State = EntityState.Detached);

            await _repository.DeleteItemAsync(sample.Id);
            Assert.That(_repository.GetItemsAsync().Result,Is.Empty);
        }

奇怪的是,如果我断开实体状态,则单元测试通过。此代码在生产中可以正常工作。我不确定哪里出了问题,我正在使用[SetUp]和[TearDown]装饰器重新创建和处置DbContext。来自Java背景,如果这很简单,请原谅我吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)