如何在实体框架中编写集成测试以测试数据是否添加到 2 个相关表

本文关键字:添加 是否 测试数据 实体 框架 集成测试 | 更新日期: 2023-09-27 18:32:07

我正在用 C# 编写集成测试,Db 正在由实体框架 6 负责。当数据添加到按键关联的 2 个表中时,我无法测试数据是否正确添加。

考虑:

 Make Table - Id, name, YearId
 Year Table - Id, CalenderYear

关系:

 1 to many - 1 Year has n Make 

这是我在集成测试中的方法,我喜欢测试是否可以成功添加到两个表中:

    [TestMethod]
    [TestCategory("Integration")]
    public void ApplicationsContext_AddMake_ShouldAddSuccessfully()
    {
        // Arrange.
        var currentEntity = ApplicationsContext.Makes.ToList<Make>();
        // Act.
        var newYear = Fakes.GetNewYear();
        ApplicationsContext.Years.Add(newYear);
        ApplicationsContext.SaveChanges();

        var newMake = Fakes.GetNewMake();
        ApplicationsContext.Makes.Add(newMake);
        ApplicationsContext.SaveChanges();
        // Assert.
        var entityAfterOperation = ApplicationsContext.Makes.ToList<Make>();
        Assert.IsTrue(currentEntity.Count < entityAfterOperation.Count);
    } 

这是我的假课:

 public static Year GetNewYear()
       {
        var newYear = new Year()
        {
            CalendarYear = 2015
        };
        return newYear;
       }
     public static Make GetNewMake()
      {
        var newMake = new Make()
        {
            Name = "Toyota",
            Description = "This is Make Description",
        };
        return newMake;
      }

这不起作用,因为我真的不知道如何发送年度 ID 制作?这是我得到的错误:

   {"Violation of UNIQUE KEY constraint 'UQ_Year_CalendarYear'. Cannot insert  duplicate key in object 'Common.Year'. The duplicate key value is (2015).'r'nThe statement has been terminated."}

如何在实体框架中编写集成测试以测试数据是否添加到 2 个相关表

当您将它们添加到数据库时,您没有关联

您正在创建的年份和 Make。

因此,在添加它们之前,您应该将newMake添加到newYear

var newYear = Fakes.GetNewYear();
newYear.Makes.Add(Fakes.GetNewMake());
ApplicationsContext.Years.Add(newYear);
ApplicationsContext.SaveChanges();

如果在保存更改之前执行此操作,则会一次性将两者添加到数据库中。