什么是模拟? [英] What is Mocking?

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

问题描述

什么是模拟?

推荐答案

序言:如果您在字典中查找名词 mock ,您会发现该词的定义之一是模仿的东西.

Prologue: If you look up the noun mock in the dictionary you will find that one of the definitions of the word is something made as an imitation.

模拟主要用于单元测试.被测对象可能依赖于其他(复杂)对象.要隔离对象的行为,您想用模拟真实对象行为的模拟替换其他对象.如果实际对象不适合合并到单元测试中,这将很有用.

Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.

简而言之,模拟就是创建模拟真实对象行为的对象.

In short, mocking is creating objects that simulate the behavior of real objects.

有时您可能想区分嘲笑 stubbing .关于这个主题可能会有一些分歧,但是我对存根的定义是最小"的模拟对象.存根实现的行为恰好足以允许被测对象执行测试.

At times you may want to distinguish between mocking as opposed to stubbing. There may be some disagreement about this subject but my definition of a stub is a "minimal" simulated object. The stub implements just enough behavior to allow the object under test to execute the test.

模拟就像存根一样,但是测试还将验证被测对象是否按预期调用了模拟.测试的一部分是验证是否正确使用了模拟.

A mock is like a stub but the test will also verify that the object under test calls the mock as expected. Part of the test is verifying that the mock was used correctly.

举个例子:您可以通过实现用于存储记录的简单内存结构来对数据库进行存根.然后,被测对象可以将记录读写到数据库存根中,以允许其执行测试.这样可以测试对象与数据库无关的某些行为,并且将包含数据库存根只是为了让测试运行.

To give an example: You can stub a database by implementing a simple in-memory structure for storing records. The object under test can then read and write records to the database stub to allow it to execute the test. This could test some behavior of the object not related to the database and the database stub would be included just to let the test run.

如果您想验证被测对象是否将某些特定数据写入数据库,则必须模拟数据库.然后,您的测试将包含有关写入数据库模拟内容的断言.

If you instead want to verify that the object under test writes some specific data to the database you will have to mock the database. Your test would then incorporate assertions about what was written to the database mock.

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

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