【发布时间】:2013-12-02 17:50:01
【问题描述】:
我想在我的 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
}
}
这引发了很多问题,这里有一个选择:如何从空数据库开始?我应该使用自己的上下文和连接字符串将另一个数据库附加到项目吗?最重要的是,如何在不破坏旧数据的情况下在实际数据库上正确测试方法?
我整天忙于弄清楚如何对我的数据库逻辑进行单元/集成测试。希望这里有经验的开发者可以提供一些帮助!
/edit 确实会影响/更改我的数据库的 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);
}
【问题讨论】:
标签: c# unit-testing asp.net-mvc-4 integration-testing