“模拟”数据库和“真正的”数据库行为之间的差异 [英] Discrepancies between “Mock” Database and “Real” database behaviours

查看:122
本文介绍了“模拟”数据库和“真正的”数据库行为之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们用C#和LINQ2SQL与MS SQL Server数据库。
我们有一个mockdatacontext进行一些单元测试。
测试时,我们发现这取决于是否使用真实或模拟数据库中的两个不同的行为。

方案1:真正的数据库

有5条记录在数据库中:

There are 5 records in the database:

db = realDatabase
db.InsertOnSubmit(new record)

var count1 = db.getTable.Count()

db.SubmitChanges()

var count2 = db.getTable.Count()

COUNT1 = < STRONG> 5
COUNT2 = 6

count1 = 5 count2 = 6

情景2:模拟数据库

有5条记录在数据库中:

There are 5 records in the database:

db= mockDatabase

db.InsertOnSubmit(new record)

var count1 = db.getTable.Count()

db.SubmitChanges()

var count2 = db.getTable.Count()

COUNT1 = 6
COUNT2 = 6

count1 = 6 count2 = 6

*模拟数据库已的SubmitChanges之前知道新纪录()被调用,因此它包括在计数。为了测试,我们需要这两种行为是一样的。

*The "mock" database is already aware of the new record before SubmitChanges() is called, so it is included in the count. For testing, we need the two behaviours to be the same.

有没有其他人遇到这个问题,你可以提出一个解决方案?

推荐答案

IMO,这是一个试图以测试来模拟一个常见的错误。 有模拟的是不是一个模拟器。它不应该执行逻辑类似于原来,它应该只返回硬编码的结果。

IMO, it is a common mistake that one tries to simulate in tests. A mock is not a simulator. It should not implement a logic that is similar to the original, it should just return hard coded results.

如果仿制品的行为是复杂的,你在测试你的模拟,而不是你的业务代码结束。

我使用RhinoMocks的,它应该是这样的:

I'm using RhinoMocks, and it would look like this:

// arrange
IList<Record> testdata = new List<Record>() {a, b, c};
db = MockRepository.GenerateMock<IDatabase>();
db.Stub(x => db.getTable).Return(testdata);

// act: call your unit under test

// assert
db.AssertWasCalled(x => x.InsertOnSubmit(Arg<Record>.Is.Anything));
db.AssertWasCalled(x => x.SubmitChanges());



它仍然返回相同的列表中的每个时间。对于许多情况下,这将是足够的。你仍然可以在第二个电话的GetTable返回其他数据:

It still returns the same list every time. For many cases, this will be sufficient. You still could return other data on the second getTable call:

db.Stub(x => db.getTable).Return(testdata1);
db.Stub(x => db.getTable).Return(testdata2);



它总是具体到一个单一的测试,但是这使得它如此简单。

It's always specific to a single test, but this makes it so simple.

编辑:

我必须承认,我不熟悉的LINQ2SQL。那些在我的例子嘲笑电话是LINQ2SQL电话,这可能不能很容易嘲笑。你可能需要把它放在一个简单的DAL接口后面。然后,你嘲笑这个接口。

I have to admit that I'm not familiar with Linq2Sql. The calls that are mocked in my example are Linq2Sql calls, which probably cannot be mocked that easily. You probably need to put it behind an simple DAL interface. Then you mock this interface.

这篇关于“模拟”数据库和“真正的”数据库行为之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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