我的DbSet 从单元测试(MSTest)代码尝试时不会更新

问题描述 投票:1回答:1

我正在对我的MVC应用程序进行单元测试。测试之一是验证我的控制器是否正确返回了提供的ID的数据。

要对其进行单元测试,我想将[TestMethod]中的数据添加到Context.DBSet,然后调用我的Controller方法并验证其输出。

但是,我添加的记录未反映在Context.DBSet对象内。

下面是我当前拥有的代码。

    ///for purpose of unit testing, there is no underlying database
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
        {
            Database.SetInitializer(new ApplicationDbContextInitializer());
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        public DbSet<Book> Books { get; set; }
        public DbSet<Customer> Customers { get; set; }
    }
    public class ApplicationDbContextInitializer : CreateDatabaseIfNotExists<ApplicationDbContext>
    {
        protected override void Seed(ApplicationDbContext context)
        {
            InitializeBooks(context);
            InitializeCustomers(context);
            base.Seed(context);
        }
    }
    //for brevity, i haven't posted the InitializeBooks & InitializeCustomers()
    //these methods create Book and Customer objects
    //and do context.Book.Add(objBook) and context.Customer.Add(objCustomer)

我的控制器类具有在MS测试中使用的DbContext对象

    public class CustomersController : Controller
    {
        public ApplicationDbContext db = new ApplicationDbContext();

        ///other methods exist too
    }

最后是我的MSTest

[TestMethod]
public void TestCustomerIDReplacedCorrectly()
{
    var objCtrl = new CustomersController();
    Customer objCust = new Customer()
    {
        Name = "Foo Bar",
        Address = "Hello World",
    };

    Console.WriteLine(objCtrl.db.Customers.Count()) //returns 4 correctly
    objCtrl.db.Customers.Add(objCust);
    Console.WriteLine(objCtrl.db.Customers.Count()) //still returns 4!? it should return 5
}

我看到添加的客户没有被Customer的DbContext对象反映在内部,因此,即使我应该验证的实际控制器方法也无法反映我想要的行为。如何确保将我的objCust添加到objCtrl.db.Customers.Add

c# asp.net-mvc entity-framework mstest dbcontext
1个回答
0
投票

您需要调用objCtrl.db.SaveChanges();才能将对象添加到DbSet。当前,您没有这样做,并且objCtrl.db.Customers.Count()向数据库查询数据库中对象[[当前存储的数量。由于尚未调用SaveChanges,因此您尚未将对象写入数据库,并且不会将其包含在.Count()方法调用中。

通常使用单独的数据库,该数据库仅用于测试,并随需要的数据(如果需要)一起播种以进行测试。通常,您会看到每个测试都封装在一个事务中,以便您可以执行所需的测试,验证数据,然后回滚所有操作,以便数据库返回到每个测试的初始状态
© www.soinside.com 2019 - 2024. All rights reserved.