What is Mocking?
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 test you replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the the real objects are impractical to incorporate into the unit test.
In short, mocking is creating objects that simulate the behavior of real objects.
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.
mocking主要用于单元测试。在测试中一个对象可能和其他复杂的对象有关联。那么为了独立这个想测试的对象,那么你就可以使用mock来替换其他的对象来模拟真实对象行为。这个很有用如果真实对象融入到test中是不切实际的话。
mocking和stubbing的区别,stub允许对象在test中执行test。mock和stub很相似但是test会verify test下的object如同预期一样调用了mock。test也verifying mock使用正确。
举例说明:你可以通过执行一个简单的结构体存储记录来stub一个数据库。object可以读取和写入记录到数据库stub中来允许他执行test。这个可以测试一些和数据库不相关的对象并且数据库stub会被包含其中来让test运行。
如果你想确认test中的对象向数据库写入了一些数据,那么你就要mock这个数据库。你的测试然后就会对写入到这个数据库mock给出assertions判断了。