我想测试我的MVC4应用程序中依赖并使用数据库的方法,我不想使用模拟方法/对象,因为查询可能很复杂,并且为此创建测试对象太费力了。
我发现了一种集成测试的思路,它将您的测试数据库操作逻辑包装在一个TransactionScope
对象中,在完成时回滚更改。
不幸的是,这不会从一开始就使用空数据库,它还会使主键计数(例如,当数据库中已经有一些带有主键1和2的项目时,运行测试后它会继续计数到4),我不想这样。
这是我想出来的“集成测试”,只是为了测试产品是否真正添加(这是一个例子,我想创建更难的测试,以检查在正确的基础设施下的方法)。
[TestMethod]
public void ProductTest()
{
// Arrange
using (new TransactionScope())
{
myContext db = new myContext();
Product testProduct = new Product
{
ProductId = 999999,
CategoryId = 3,
ShopId = 2,
Price = 1.00M,
Name = "Test Product",
Visible = true
};
// Act
db.Products.Add(testProduct);
db.SaveChanges();
// Assert
Assert.AreEqual(1, db.Products.ToList().Count());
// Fails since there are already items in database
}
}
这引起了许多问题,以下是其中一些:如何从空数据库开始?是否应该将另一个带有自己上下文和连接字符串的数据库附加到项目中?最重要的是,如何在实际数据库上正确测试方法而不破坏我的旧数据?
我一整天都忙于尝试解决如何对数据库逻辑进行单元/集成测试的问题。希望这里有一些有经验的开发人员能够提供一些帮助!
/编辑:NDbUnit 测试确实影响/更改了我的数据库...
public class IntegrationTests
{
[TestMethod]
public void Test()
{
string connectionString = "Data Source=(LocalDb)\\v11.0;Initial Catalog=Database_Nieuw;
Integrated Security=false;";
//The above is the only connectionstring that works... And is the "real" local database
//This is not used on Jenkins but I can perhaps attach it???
NDbUnit.Core.INDbUnitTest mySqlDatabase = new
NDbUnit.Core.SqlClient.SqlDbUnitTest(connectionString);
mySqlDatabase.ReadXmlSchema(@"..\..\NDbUnitTestDatabase\NDbUnitTestDatabase.xsd");
mySqlDatabase.ReadXml(@"..\..\NDbUnitTestDatabase\DatabaseSeeding.xml"); // The data
mySqlDatabase.PerformDbOperation(NDbUnit.Core.DbOperationFlag.CleanInsertIdentity);
}