我正在对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)
我的Controller类具有DbContext对象,我可以在MS Test中使用它
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
///calls are given to controller method
///to fetch ViewResult and ViewBag
///to validate if it is processing the
///instance put inside the objCtrl.db.Customers
}
我看到添加的客户没有被Customer的DbContext对象反映在内部,因此,即使我应该验证的实际控制器方法也无法反映我想要的行为。如何确保将我的objCust
添加到objCtrl.db.Customers.Add
这是InitializeCustomers()代码,它被称为种子输入
private void InitializeCustomers(ApplicationDbContext context)
{
Customer cust1 = new Customer()
{
Name = "James Butt",Address = "6649 N Blue Gum St",Contact = "50-621 8927",NationalID = "12312312312"
};
Customer cust2 = new Customer()
{
Name = "Josephine Darakjy",Address = "Chanay,Jeffrey A Esq",Contact = "81-292 9840",NationalID = "123123124"
};
Customer cust3 = new Customer()
{
Name = "Art Venere",Address = "Chemel,James L Cpa",Contact = "85-636 8749",NationalID = "123123456"
};
Customer cust4 = new Customer()
{
Name = "Lenna Paprocki",Address = "Feltz Printing Service",Contact = "90-385 4412",NationalID = "32165498712"
};
context.Customers.Add(cust1);
context.Customers.Add(cust2);
context.Customers.Add(cust3);
context.Customers.Add(cust4);
}