我一直在寻找一种有效的方法来单元测试C#中的数据访问层。我主要是Java开发人员,只使用C#约6个月,在过去,我使用了一个叫做DBUnit的库来测试已知状态数据库。我还没有找到类似的活跃库,最接近的似乎是nDBUnit,但它已经有一段时间没有更新了。
在C#中,似乎存在很多矛盾的方法和原因。理想情况下,我希望使用模拟测试数据访问层,而不需要连接到数据库,然后在单独的测试集中对存储过程进行单元测试。
在我正在处理的系统中,数据访问层使用ADO.net(不使用Entity Framework)来调用SQL Server上的存储过程。
下面是一个示例代码,我需要使用模拟对象来模拟SqlCommand(使用IDbCommand)和/或模拟SqlConnection。
因此我的问题是,如果有这样的东西,最好的方法似乎是什么?到目前为止,唯一的方法是创建代理对象,该对象传递到构造函数中,以便可以返回模拟的Sql*对象进行测试。
在C#中,似乎存在很多矛盾的方法和原因。理想情况下,我希望使用模拟测试数据访问层,而不需要连接到数据库,然后在单独的测试集中对存储过程进行单元测试。
在我正在处理的系统中,数据访问层使用ADO.net(不使用Entity Framework)来调用SQL Server上的存储过程。
下面是一个示例代码,我需要使用模拟对象来模拟SqlCommand(使用IDbCommand)和/或模拟SqlConnection。
因此我的问题是,如果有这样的东西,最好的方法似乎是什么?到目前为止,唯一的方法是创建代理对象,该对象传递到构造函数中,以便可以返回模拟的Sql*对象进行测试。
我还没有机会查看所有可用的C#模拟库。
public class CustomerRepository : ICustomerRepository
{
private string connectionString;
public CustomerRepository (string connectionString)
{
this.connectionString = connectionString;
}
public int Create(Customer customer)
{
SqlParameter paramOutId = new SqlParameter("@out_id", SqlDbType.Int);
paramOutId.Direction = ParameterDirection.Output;
List<SqlParameter> sqlParams = new List<SqlParameter>()
{
paramOutId,
new SqlParameter("@name", customer.Name)
}
SqlConnection connection = GetConnection();
try
{
SqlCommand command = new SqlCommand("store_proc_name", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddRange(sqlParams.ToArray());
int results = command.ExecuteNonQuery();
return (int) paramOutId.Value;
}
finally
{
CloseConnection(connection);
}
}
}