【发布时间】:2016-08-15 12:14:50
【问题描述】:
过去,当我一直在实施单元测试时,我一直在努力为数据访问层设置“体面”的单元测试,因为它们通常将数据库作为外部依赖项。在理想的世界中,我会模拟存储过程调用,以便删除外部依赖项。
但是,我无法弄清楚如何使用 MOQ 模拟框架来执行此操作,或者找到任何其他支持此功能的框架。相反,我已经恢复为使用已知数据创建脚本测试数据库(这样我总是可以得到我期望的输出),但这与模拟该层略有不同。
谁能建议如何模拟这部分数据访问层[我知道实体框架https://effort.codeplex.com/ 存在]?
详情 例如,如果我有以下方法
public object RunStoredProc()
{
//Some Setup
using (SqlConnection conn = new SqlConnection(CONNNECTION_STRING))
{
using (SqlCommand comm = new SqlCommand("storedProcName", conn))
{
conn.Open();
comm.CommandType = CommandType.StoredProcedure;
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
//Logic
}
}
}
}
//Return object based on logic
}
那么我如何模拟存储过程输出,以便SQLDataReader 包含指定的数据。在更高的层次上,我可以模拟RunStoredProc() 方法——但这无助于我测试该方法中的逻辑是否正确。或者,我可以将SQLReader 剥离到另一种方法中
public object RunStoredProc()
{
//Some Setup
List<object> data = GetData();
//Logic
//Return object based on logic
}
private List<object> GetData()
{
using (SqlConnection conn = new SqlConnection(CONNNECTION_STRING))
{
using (SqlCommand comm = new SqlCommand("storedProcName", conn))
{
conn.Open();
comm.CommandType = CommandType.StoredProcedure;
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
//place into return object
}
}
}
}
}
但由于“GetData”方法应该是私有的(不是已发布接口的一部分),因此我无法模拟它,因此问题仍然存在。
【问题讨论】:
标签: c# unit-testing stored-procedures mocking system.data