如何在Entity Framework中编写集成测试以测试数据是否添加到2个相关表中?

时间:2016-01-27 20:05:27

标签: c# entity-framework integration-testing

我正在用C#编写集成测试,Db正在由Entity Framework6负责。我有测试的问题如果数据被添加到按键相关的2个表中时数据正确添加。

考虑:

 Make Table - Id, name, YearId

 Year Table - Id, CalenderYear

关系:

 1 to many - 1 Year has n Make 

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

    [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."}

1 个答案:

答案 0 :(得分:1)

您未将年份与年份相关联并在您将其添加到数据库时创建。

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

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

ApplicationsContext.Years.Add(newYear);
ApplicationsContext.SaveChanges();

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