如何正确插入外键的单元测试

时间:2014-04-02 05:22:32

标签: entity-framework unit-testing

我有一个订单,它有很多订单,现在外键是按顺序生成的,所以我必须检查每个订单项是否获得正确的订单外键。这意味着订单中的订单应该等于特定的订单。应该断言?

My Domain类如下

public class Order

{

    public int Id { get; set; }
    public Employee Employee { get; set; }
    public Location FromLocation { get; set; }
    public Location ToLocation { get; set; }
    public DateTime OrderDate { get; set; }
    public List<OrderItem> OrderItems { get; set; }
    public List<OrderDispatch> OrderDispatches { get; set; }
    public OrderStatus Status { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int Quantity { get; set; }
    public Order Order { get; set; }
    public Product Product { get; set; }


}



[TestMethod]

public void OrderItemsAreAssignProperOrderId()
{

   using (var db = new StockWatchContext())

   {

            Order o = new Order();



            o.OrderDate = DateTime.Now;
            o.Status = OrderStatus.Open;
            o.Employee = db.Employees.Find(8);
            o.FromLocation = db.Locations.Find(4);
            o.ToLocation = db.Locations.Find(1);

            o.OrderItems = new List<OrderItem> {
            new OrderItem {Product = db.Products.Find(1), Quantity = 10}, 

            };

            db.Orders.Add(o);


            db.SaveChanges();

            Assert.AreEqual();

        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

如果您正在测试专用于测试的数据库,则可以在每个TestMethod之前清空表。

然后在OrderItemsAreAssignProperOrderId()方法中的SaveChanges之后检查OrderItem表中的所有行是否具有正确的Order id。