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