用Moq模拟数据集 [英] Mocking Datasets with Moq

查看:98
本文介绍了用Moq模拟数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开始使用Moq,但找不到任何好的资源来做我需要的事情.

I'm trying to get started with Moq and having trouble finding any good resources to do what I need.

我有一个数据接口类,该类具有一个Get方法,该方法通过存储过程返回一个数据集.这是编写代码的方式,目前我无法对其进行更改,因此必须以这种方式进行.

I have a Data Interface class that has a Get method which returns a Dataset via Stored Procedure. This is the way the code was written and I can't change it at the moment so it has to be done this way.

我想通过模拟数据集并返回数据来测试此类,因此我实际上不必进行数据库调用.

I want to test this class by Mocking the Dataset and returning data so I don't have to actually make a database call.

有人在这样做吗?如果是这样,哪里有个开始的好地方呢?

Is anyone doing this and if so where is a good place to get started doing it?

推荐答案

您不需要数据库连接即可填充数据集.您可以这样模拟它:

You don't need a database connection to fill in a DataSet. You can mock it like this:

IDataInterface di = new Mock<IDataInterface>();
DataSet mockDataSet = CreateMockDataSet();
di.Expect(x => x.Get()).Returns(mockDataSet);
something.UseDataInterface(di.Object);

但是,在模拟数据集中填充是非常痛苦的.如果执行此操作,通常会在返回的DataSet前面放置一个Facade接口,这更易于模拟.或者我将代码更改为使用DataTable,这更容易填写.

Filling in a mock DataSet is quite painful, though. If I'm doing this, I generally put a facade interface in front of the returned DataSet, which is easier to mock. Or I change the code to use a DataTable, which is easier to fill in.

或者,将嵌入式数据库(例如SQLite或SQL Server CE)用于单元测试.

Alternatively, use an embedded database, such as SQLite or SQL Server CE, for your unit tests.

这篇关于用Moq模拟数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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