使用内存中数据集(或类似数据)作为源的不带Db的DbConnection [英] DbConnection without Db using in-memory DataSet (or similar) as source

查看:92
本文介绍了使用内存中数据集(或类似数据)作为源的不带Db的DbConnection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对一些.NET类进行单元测试(出于良好的设计原因),这些类需要DbConnections来完成其工作.对于这些测试,我在内存中有某些数据可以作为这些类的输入.

I'm trying to unit test a few .NET classes that (for good design reasons) require DbConnections to do their work. For these tests, I have certain data in memory to give as input to these classes.

该内存中的数据可以很容易地表示为DataTable(或包含该DataTable的DataSet),但是如果另一个类更合适,我可以使用它.

That in-memory data could be easily expressed as a DataTable (or a DataSet that contains that DataTable), but if another class were more appropriate I could use it.

如果我能够以某种方式神奇地获得代表内存数据连接的DbConnection,那么我可以构造我的对象,让它们对内存数据执行查询,并确保其输出符合期望. 是否可以通过某种方式获得DbConnection到内存中的数据?我没有自由安装任何其他第三方软件来实现此目的,并且理想情况下,我不想在测试过程中触摸磁盘.

If I were somehow magically able to get a DbConnection that represented a connection to the in-memory data, then I could construct my objects, have them execute their queries against the in-memory data, and ensure that their output matched expectations. Is there some way to get a DbConnection to in-memory data? I don't have the freedom to install any additional third-party software to make this happen, and ideally, I don't want to touch the disk during the tests.

推荐答案

除了消耗DbConnection之外,您还可以消耗IDbConnection并对其进行模拟吗?我们做类似的事情,将模拟传递给DataSet. DataSet.CreateDataReader返回从DbDataReader继承的DataTableReader.

Rather than consume a DbConnection can you consume IDbConnection and mock it? We do something similar, pass the mock a DataSet. DataSet.CreateDataReader returns a DataTableReader which inherits from DbDataReader.

我们已经将DbConnection包装在我们自己的类似IDbConnection的接口中,在该接口中添加了ExecuteReader()方法,该方法返回一个实现与DbDataReader相同的接口的类.在我们的模拟中,ExecuteReader只是返回DataSet.CreateDataReader服务的内容.

We have wrapped DbConnection in our own IDbConnection-like interface to which we've added an ExecuteReader() method which returns a class that implements the same interfaces as DbDataReader. In our mock, ExecuteReader simply returns what DataSet.CreateDataReader serves up.

听起来有点回旋,但是使用可能有很多结果集的数据集构建起来非常方便.我们以代表它们的结果的存储过程命名数据表,并且我们的IDbConnection模拟根据客户端正在调用的过程获取正确的数据表. DataTable还实现了CreateDataReader,所以我们很高兴.

Sounds kind of roundabout, but it is very convenient to build up a DataSet with possibly many resultsets. We name the DataTables after the stored procs that they represent the results of, and our IDbConnection mock grabs the right Datatable based on the proc the client is calling. DataTable also implements CreateDataReader so we're good to go.

这篇关于使用内存中数据集(或类似数据)作为源的不带Db的DbConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆